-
Notifications
You must be signed in to change notification settings - Fork 7.6k
Expand file tree
/
Copy pathOperatorScan.java
More file actions
345 lines (311 loc) · 11.3 KB
/
OperatorScan.java
File metadata and controls
345 lines (311 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/**
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rx.internal.operators;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicLong;
import rx.*;
import rx.Observable.Operator;
import rx.exceptions.Exceptions;
import rx.functions.*;
import rx.internal.util.atomic.SpscLinkedAtomicQueue;
import rx.internal.util.unsafe.*;
/**
* Returns an Observable that applies a function to the first item emitted by a source Observable, then feeds
* the result of that function along with the second item emitted by an Observable into the same function, and
* so on until all items have been emitted by the source Observable, emitting the result of each of these
* iterations.
* <p>
* <img width="640" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/scan.png" alt="">
* <p>
* This sort of function is sometimes called an accumulator.
* <p>
* Note that when you pass a seed to {@code scan} the resulting Observable will emit that seed as its
* first emitted item.
*
* @param <R> the aggregate and output type
* @param <T> the input value type
*/
public final class OperatorScan<R, T> implements Operator<R, T> {
private final Func0<R> initialValueFactory;
final Func2<R, ? super T, R> accumulator;
// sentinel if we don't receive an initial value
private static final Object NO_INITIAL_VALUE = new Object();
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result with the
* specified source and accumulator.
*
* @param initialValue
* the initial (seed) accumulator value
* @param accumulator
* an accumulator function to be invoked on each element from the sequence
* @see <a href="http://msdn.microsoft.com/en-us/library/hh212007.aspx">Observable.Scan(TSource, TAccumulate) Method (IObservable(TSource), TAccumulate, Func(TAccumulate, TSource,
* TAccumulate))</a>
*/
public OperatorScan(final R initialValue, Func2<R, ? super T, R> accumulator) {
this(new Func0<R>() {
@Override
public R call() {
return initialValue;
}
}, accumulator);
}
public OperatorScan(Func0<R> initialValueFactory, Func2<R, ? super T, R> accumulator) {
this.initialValueFactory = initialValueFactory;
this.accumulator = accumulator;
}
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result with the
* specified source and accumulator.
*
* @param accumulator
* an accumulator function to be invoked on each element from the sequence
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211665.aspx">Observable.Scan(TSource) Method (IObservable(TSource), Func(TSource, TSource, TSource))</a>
*/
@SuppressWarnings("unchecked")
public OperatorScan(final Func2<R, ? super T, R> accumulator) {
this((R) NO_INITIAL_VALUE, accumulator);
}
@Override
public Subscriber<? super T> call(final Subscriber<? super R> child) {
final R initialValue = initialValueFactory.call();
if (initialValue == NO_INITIAL_VALUE) {
return new Subscriber<T>(child) {
boolean once;
R value;
@SuppressWarnings("unchecked")
@Override
public void onNext(T t) {
R v;
if (!once) {
once = true;
v = (R)t;
} else {
v = value;
try {
v = accumulator.call(v, t);
} catch (Throwable e) {
Exceptions.throwOrReport(e, child, t);
return;
}
}
value = v;
child.onNext(v);
}
@Override
public void onError(Throwable e) {
child.onError(e);
}
@Override
public void onCompleted() {
child.onCompleted();
}
};
}
final InitialProducer<R> ip = new InitialProducer<R>(initialValue, child);
Subscriber<T> parent = new Subscriber<T>() {
private R value = initialValue;
@Override
public void onNext(T currentValue) {
R v = value;
try {
v = accumulator.call(v, currentValue);
} catch (Throwable e) {
Exceptions.throwOrReport(e, this, currentValue);
return;
}
value = v;
ip.onNext(v);
}
@Override
public void onError(Throwable e) {
ip.onError(e);
}
@Override
public void onCompleted() {
ip.onCompleted();
}
@Override
public void setProducer(final Producer producer) {
ip.setProducer(producer);
}
};
child.add(parent);
child.setProducer(ip);
return parent;
}
static final class InitialProducer<R> implements Producer, Observer<R> {
final Subscriber<? super R> child;
final Queue<Object> queue;
boolean emitting;
/** Missed a terminal event. */
boolean missed;
/** Missed a request. */
long missedRequested;
/** The current requested amount. */
final AtomicLong requested;
/** The current producer. */
volatile Producer producer;
volatile boolean done;
Throwable error;
public InitialProducer(R initialValue, Subscriber<? super R> child) {
this.child = child;
Queue<Object> q;
// TODO switch to the linked-array based queue once available
if (UnsafeAccess.isUnsafeAvailable()) {
q = new SpscLinkedQueue<Object>(); // new SpscUnboundedArrayQueue<R>(8);
} else {
q = new SpscLinkedAtomicQueue<Object>(); // new SpscUnboundedAtomicArrayQueue<R>(8);
}
this.queue = q;
q.offer(NotificationLite.next(initialValue));
this.requested = new AtomicLong();
}
@Override
public void onNext(R t) {
queue.offer(NotificationLite.next(t));
emit();
}
boolean checkTerminated(boolean d, boolean empty, Subscriber<? super R> child) {
if (child.isUnsubscribed()) {
return true;
}
if (d) {
Throwable err = error;
if (err != null) {
child.onError(err);
return true;
} else
if (empty) {
child.onCompleted();
return true;
}
}
return false;
}
@Override
public void onError(Throwable e) {
error = e;
done = true;
emit();
}
@Override
public void onCompleted() {
done = true;
emit();
}
@Override
public void request(long n) {
if (n < 0L) {
throw new IllegalArgumentException("n >= required but it was " + n);
} else
if (n != 0L) {
BackpressureUtils.getAndAddRequest(requested, n);
Producer p = producer;
if (p == null) {
// not synchronizing on this to avoid clash with emit()
synchronized (requested) {
p = producer;
if (p == null) {
long mr = missedRequested;
missedRequested = BackpressureUtils.addCap(mr, n);
}
}
}
if (p != null) {
p.request(n);
}
emit();
}
}
public void setProducer(Producer p) {
if (p == null) {
throw new NullPointerException();
}
long mr;
// not synchronizing on this to avoid clash with emit()
synchronized (requested) {
if (producer != null) {
throw new IllegalStateException("Can't set more than one Producer!");
}
mr = missedRequested;
// request one less because of the initial value, this happens once
// and is performed only if the request is not at MAX_VALUE already
if (mr != Long.MAX_VALUE) {
mr -= 1;
}
missedRequested = 0L;
producer = p;
}
if (mr > 0L) {
p.request(mr);
}
emit();
}
void emit() {
synchronized (this) {
if (emitting) {
missed = true;
return;
}
emitting = true;
}
emitLoop();
}
void emitLoop() {
final Subscriber<? super R> child = this.child;
final Queue<Object> queue = this.queue;
AtomicLong requested = this.requested;
long r = requested.get();
for (;;) {
boolean d = done;
boolean empty = queue.isEmpty();
if (checkTerminated(d, empty, child)) {
return;
}
long e = 0L;
while (e != r) {
d = done;
Object o = queue.poll();
empty = o == null;
if (checkTerminated(d, empty, child)) {
return;
}
if (empty) {
break;
}
R v = NotificationLite.getValue(o);
try {
child.onNext(v);
} catch (Throwable ex) {
Exceptions.throwOrReport(ex, child, v);
return;
}
e++;
}
if (e != 0 && r != Long.MAX_VALUE) {
r = BackpressureUtils.produced(requested, e);
}
synchronized (this) {
if (!missed) {
emitting = false;
return;
}
missed = false;
}
}
}
}
}