Debian Codegraph @

src/main/java/io/reactivex/rxjava3/processors/AsyncProcessor.java

raw
1 /*
2 * Copyright (c) 2016-present, RxJava Contributors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
5 * compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License is
10 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
11 * the License for the specific language governing permissions and limitations under the License.
12 */
13
14 package io.reactivex.rxjava3.processors;
15
16 import java.util.concurrent.atomic.AtomicReference;
17
18 import org.reactivestreams.*;
19
20 import io.reactivex.rxjava3.annotations.*;
21 import io.reactivex.rxjava3.internal.subscriptions.DeferredScalarSubscription;
22 import io.reactivex.rxjava3.internal.util.ExceptionHelper;
23 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
24
25 /**
26 * Processor that emits the very last value followed by a completion event or the received error
27 * to {@link Subscriber}s.
28 * <p>
29 * <img width="640" height="239" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/AsyncProcessor.png" alt="">
30 * <p>
31 * This processor does not have a public constructor by design; a new empty instance of this
32 * {@code AsyncProcessor} can be created via the {@link #create()} method.
33 * <p>
34 * Since an {@code AsyncProcessor} is a Reactive Streams {@code Processor} type,
35 * {@code null}s are not allowed (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.13">Rule 2.13</a>)
36 * as parameters to {@link #onNext(Object)} and {@link #onError(Throwable)}. Such calls will result in a
37 * {@link NullPointerException} being thrown and the processor's state is not changed.
38 * <p>
39 * {@code AsyncProcessor} is a {@link io.reactivex.rxjava3.core.Flowable} as well as a {@link FlowableProcessor} and supports backpressure from the downstream but
40 * its {@link Subscriber}-side consumes items in an unbounded manner.
41 * <p>
42 * When this {@code AsyncProcessor} is terminated via {@link #onError(Throwable)}, the
43 * last observed item (if any) is cleared and late {@link Subscriber}s only receive
44 * the {@code onError} event.
45 * <p>
46 * The {@code AsyncProcessor} caches the latest item internally and it emits this item only when {@code onComplete} is called.
47 * Therefore, it is not recommended to use this {@code Processor} with infinite or never-completing sources.
48 * <p>
49 * Even though {@code AsyncProcessor} implements the {@link Subscriber} interface, calling
50 * {@code onSubscribe} is not required (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.12">Rule 2.12</a>)
51 * if the processor is used as a standalone source. However, calling {@code onSubscribe}
52 * after the {@code AsyncProcessor} reached its terminal state will result in the
53 * given {@link Subscription} being canceled immediately.
54 * <p>
55 * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()}
56 * is required to be serialized (called from the same thread or called non-overlappingly from different threads
57 * through external means of serialization). The {@link #toSerialized()} method available to all {@code FlowableProcessor}s
58 * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Subscriber}
59 * consuming this processor also wants to call {@link #onNext(Object)} on this processor recursively).
60 * The implementation of {@code onXXX} methods are technically thread-safe but non-serialized calls
61 * to them may lead to undefined state in the currently subscribed {@code Subscriber}s.
62 * <p>
63 * This {@code AsyncProcessor} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()},
64 * {@link #getThrowable()} and {@link #hasSubscribers()} as well as means to read the very last observed value -
65 * after this {@code AsyncProcessor} has been completed - in a non-blocking and thread-safe
66 * manner via {@link #hasValue()} or {@link #getValue()}.
67 * <dl>
68 * <dt><b>Backpressure:</b></dt>
69 * <dd>The {@code AsyncProcessor} honors the backpressure of the downstream {@code Subscriber}s and won't emit
70 * its single value to a particular {@code Subscriber} until that {@code Subscriber} has requested an item.
71 * When the {@code AsyncProcessor} is subscribed to a {@link io.reactivex.rxjava3.core.Flowable}, the processor consumes this
72 * {@code Flowable} in an unbounded manner (requesting {@link Long#MAX_VALUE}) as only the very last upstream item is
73 * retained by it.
74 * </dd>
75 * <dt><b>Scheduler:</b></dt>
76 * <dd>{@code AsyncProcessor} does not operate by default on a particular {@link io.reactivex.rxjava3.core.Scheduler} and
77 * the {@code Subscriber}s get notified on the thread where the terminating {@code onError} or {@code onComplete}
78 * methods were invoked.</dd>
79 * <dt><b>Error handling:</b></dt>
80 * <dd>When the {@link #onError(Throwable)} is called, the {@code AsyncProcessor} enters into a terminal state
81 * and emits the same {@code Throwable} instance to the last set of {@code Subscriber}s. During this emission,
82 * if one or more {@code Subscriber}s dispose their respective {@code Subscription}s, the
83 * {@code Throwable} is delivered to the global error handler via
84 * {@link io.reactivex.rxjava3.plugins.RxJavaPlugins#onError(Throwable)} (multiple times if multiple {@code Subscriber}s
85 * cancel at once).
86 * If there were no {@code Subscriber}s subscribed to this {@code AsyncProcessor} when the {@code onError()}
87 * was called, the global error handler is not invoked.
88 * </dd>
89 * </dl>
90 * <p>
91 * Example usage:
92 * <pre><code>
93 * AsyncProcessor&lt;Object&gt; processor = AsyncProcessor.create();
94 *
95 * TestSubscriber&lt;Object&gt; ts1 = processor.test();
96 *
97 * ts1.assertEmpty();
98 *
99 * processor.onNext(1);
100 *
101 * // AsyncProcessor only emits when onComplete was called.
102 * ts1.assertEmpty();
103 *
104 * processor.onNext(2);
105 * processor.onComplete();
106 *
107 * // onComplete triggers the emission of the last cached item and the onComplete event.
108 * ts1.assertResult(2);
109 *
110 * TestSubscriber&lt;Object&gt; ts2 = processor.test();
111 *
112 * // late Subscribers receive the last cached item too
113 * ts2.assertResult(2);
114 * </code></pre>
115 * @param <T> the value type
116 */
117 public final class AsyncProcessor<@NonNull T> extends FlowableProcessor<T> {
118
119 @SuppressWarnings("rawtypes")
120 static final AsyncSubscription[] EMPTY = new AsyncSubscription[0];
121
122 @SuppressWarnings("rawtypes")
123 static final AsyncSubscription[] TERMINATED = new AsyncSubscription[0];
124
125 final AtomicReference<AsyncSubscription<T>[]> subscribers;
126
127 /** Write before updating subscribers, read after reading subscribers as TERMINATED. */
128 Throwable error;
129
130 /** Write before updating subscribers, read after reading subscribers as TERMINATED. */
131 T value;
132
133 /**
134 * Creates a new AsyncProcessor.
135 * @param <T> the value type to be received and emitted
136 * @return the new AsyncProcessor instance
137 */
138 @CheckReturnValue
139 @NonNull
140 public static <T> AsyncProcessor<T> create() {
141 return new AsyncProcessor<>();
142 }
143
144 /**
145 * Constructs an AsyncProcessor.
146 * @since 2.0
147 */
148 @SuppressWarnings("unchecked")
149 AsyncProcessor() {
150 this.subscribers = new AtomicReference<>(EMPTY);
151 }
152
153 @Override
154 public void onSubscribe(@NonNull Subscription s) {
155 if (subscribers.get() == TERMINATED) {
156 s.cancel();
157 return;
158 }
159 // AsyncProcessor doesn't bother with request coordination.
160 s.request(Long.MAX_VALUE);
161 }
162
163 @Override
164 public void onNext(@NonNull T t) {
165 ExceptionHelper.nullCheck(t, "onNext called with a null value.");
166 if (subscribers.get() == TERMINATED) {
167 return;
168 }
169 value = t;
170 }
171
172 @SuppressWarnings("unchecked")
173 @Override
174 public void onError(@NonNull Throwable t) {
175 ExceptionHelper.nullCheck(t, "onError called with a null Throwable.");
176 if (subscribers.get() == TERMINATED) {
177 RxJavaPlugins.onError(t);
178 return;
179 }
180 value = null;
181 error = t;
182 for (AsyncSubscription<T> as : subscribers.getAndSet(TERMINATED)) {
183 as.onError(t);
184 }
185 }
186
187 @SuppressWarnings("unchecked")
188 @Override
189 public void onComplete() {
190 if (subscribers.get() == TERMINATED) {
191 return;
192 }
193 T v = value;
194 AsyncSubscription<T>[] array = subscribers.getAndSet(TERMINATED);
195 if (v == null) {
196 for (AsyncSubscription<T> as : array) {
197 as.onComplete();
198 }
199 } else {
200 for (AsyncSubscription<T> as : array) {
201 as.complete(v);
202 }
203 }
204 }
205
206 @Override
207 @CheckReturnValue
208 public boolean hasSubscribers() {
209 return subscribers.get().length != 0;
210 }
211
212 @Override
213 @CheckReturnValue
214 public boolean hasThrowable() {
215 return subscribers.get() == TERMINATED && error != null;
216 }
217
218 @Override
219 @CheckReturnValue
220 public boolean hasComplete() {
221 return subscribers.get() == TERMINATED && error == null;
222 }
223
224 @Override
225 @Nullable
226 @CheckReturnValue
227 public Throwable getThrowable() {
228 return subscribers.get() == TERMINATED ? error : null;
229 }
230
231 @Override
232 protected void subscribeActual(@NonNull Subscriber<? super T> s) {
233 AsyncSubscription<T> as = new AsyncSubscription<>(s, this);
234 s.onSubscribe(as);
235 if (add(as)) {
236 if (as.isCancelled()) {
237 remove(as);
238 }
239 } else {
240 Throwable ex = error;
241 if (ex != null) {
242 s.onError(ex);
243 } else {
244 T v = value;
245 if (v != null) {
246 as.complete(v);
247 } else {
248 as.onComplete();
249 }
250 }
251 }
252 }
253
254 /**
255 * Tries to add the given subscriber to the subscribers array atomically
256 * or returns false if the processor has terminated.
257 * @param ps the subscriber to add
258 * @return true if successful, false if the processor has terminated
259 */
260 boolean add(AsyncSubscription<T> ps) {
261 for (;;) {
262 AsyncSubscription<T>[] a = subscribers.get();
263 if (a == TERMINATED) {
264 return false;
265 }
266
267 int n = a.length;
268 @SuppressWarnings("unchecked")
269 AsyncSubscription<T>[] b = new AsyncSubscription[n + 1];
270 System.arraycopy(a, 0, b, 0, n);
271 b[n] = ps;
272
273 if (subscribers.compareAndSet(a, b)) {
274 return true;
275 }
276 }
277 }
278
279 /**
280 * Atomically removes the given subscriber if it is subscribed to this processor.
281 * @param ps the subscriber's subscription wrapper to remove
282 */
283 @SuppressWarnings("unchecked")
284 void remove(AsyncSubscription<T> ps) {
285 for (;;) {
286 AsyncSubscription<T>[] a = subscribers.get();
287 int n = a.length;
288 if (n == 0) {
289 return;
290 }
291
292 int j = -1;
293 for (int i = 0; i < n; i++) {
294 if (a[i] == ps) {
295 j = i;
296 break;
297 }
298 }
299
300 if (j < 0) {
301 return;
302 }
303
304 AsyncSubscription<T>[] b;
305
306 if (n == 1) {
307 b = EMPTY;
308 } else {
309 b = new AsyncSubscription[n - 1];
310 System.arraycopy(a, 0, b, 0, j);
311 System.arraycopy(a, j + 1, b, j, n - j - 1);
312 }
313 if (subscribers.compareAndSet(a, b)) {
314 return;
315 }
316 }
317 }
318
319 /**
320 * Returns true if this processor has any value.
321 * <p>The method is thread-safe.
322 * @return true if this processor has any value
323 */
324 @CheckReturnValue
325 public boolean hasValue() {
326 return subscribers.get() == TERMINATED && value != null;
327 }
328
329 /**
330 * Returns a single value this processor currently has or null if no such value exists.
331 * <p>The method is thread-safe.
332 * @return a single value this processor currently has or null if no such value exists
333 */
334 @Nullable
335 @CheckReturnValue
336 public T getValue() {
337 return subscribers.get() == TERMINATED ? value : null;
338 }
339
340 static final class AsyncSubscription<@NonNull T> extends DeferredScalarSubscription<T> {
341 private static final long serialVersionUID = 5629876084736248016L;
342
343 final AsyncProcessor<T> parent;
344
345 AsyncSubscription(Subscriber<? super T> actual, AsyncProcessor<T> parent) {
346 super(actual);
347 this.parent = parent;
348 }
349
350 @Override
351 public void cancel() {
352 if (super.tryCancel()) {
353 parent.remove(this);
354 }
355 }
356
357 void onComplete() {
358 if (!isCancelled()) {
359 downstream.onComplete();
360 }
361 }
362
363 void onError(Throwable t) {
364 if (isCancelled()) {
365 RxJavaPlugins.onError(t);
366 } else {
367 downstream.onError(t);
368 }
369 }
370 }
371 }