Debian Codegraph @

src/main/java/io/reactivex/rxjava3/subjects/UnicastSubject.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.subjects;
15
16 import java.util.Objects;
17 import java.util.concurrent.atomic.*;
18
19 import io.reactivex.rxjava3.annotations.*;
20 import io.reactivex.rxjava3.core.Observer;
21 import io.reactivex.rxjava3.disposables.Disposable;
22 import io.reactivex.rxjava3.internal.disposables.EmptyDisposable;
23 import io.reactivex.rxjava3.internal.functions.*;
24 import io.reactivex.rxjava3.internal.observers.BasicIntQueueDisposable;
25 import io.reactivex.rxjava3.internal.util.ExceptionHelper;
26 import io.reactivex.rxjava3.operators.SimpleQueue;
27 import io.reactivex.rxjava3.operators.SpscLinkedArrayQueue;
28 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
29
30 /**
31 * A Subject that queues up events until a single {@link Observer} subscribes to it, replays
32 * those events to it until the {@code Observer} catches up and then switches to relaying events live to
33 * this single {@code Observer} until this {@code UnicastSubject} terminates or the {@code Observer} disposes.
34 * <p>
35 * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/UnicastSubject.png" alt="">
36 * <p>
37 * Note that {@code UnicastSubject} holds an unbounded internal buffer.
38 * <p>
39 * This subject does not have a public constructor by design; a new empty instance of this
40 * {@code UnicastSubject} can be created via the following {@code create} methods that
41 * allow specifying the retention policy for items:
42 * <ul>
43 * <li>{@link #create()} - creates an empty, unbounded {@code UnicastSubject} that
44 * caches all items and the terminal event it receives.</li>
45 * <li>{@link #create(int)} - creates an empty, unbounded {@code UnicastSubject}
46 * with a hint about how many <b>total</b> items one expects to retain.</li>
47 * <li>{@link #create(boolean)} - creates an empty, unbounded {@code UnicastSubject} that
48 * optionally delays an error it receives and replays it after the regular items have been emitted.</li>
49 * <li>{@link #create(int, Runnable)} - creates an empty, unbounded {@code UnicastSubject}
50 * with a hint about how many <b>total</b> items one expects to retain and a callback that will be
51 * called exactly once when the {@code UnicastSubject} gets terminated or the single {@code Observer} disposes.</li>
52 * <li>{@link #create(int, Runnable, boolean)} - creates an empty, unbounded {@code UnicastSubject}
53 * with a hint about how many <b>total</b> items one expects to retain and a callback that will be
54 * called exactly once when the {@code UnicastSubject} gets terminated or the single {@code Observer} disposes
55 * and optionally delays an error it receives and replays it after the regular items have been emitted.</li>
56 * </ul>
57 * <p>
58 * If more than one {@code Observer} attempts to subscribe to this {@code UnicastSubject}, they
59 * will receive an {@code IllegalStateException} indicating the single-use-only nature of this {@code UnicastSubject},
60 * even if the {@code UnicastSubject} already terminated with an error.
61 * <p>
62 * Since a {@code Subject} is conceptionally derived from the {@code Processor} type in the Reactive Streams specification,
63 * {@code null}s are not allowed (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.13">Rule 2.13</a>) as
64 * parameters to {@link #onNext(Object)} and {@link #onError(Throwable)}. Such calls will result in a
65 * {@link NullPointerException} being thrown and the subject's state is not changed.
66 * <p>
67 * Since a {@code UnicastSubject} is an {@link io.reactivex.rxjava3.core.Observable}, it does not support backpressure.
68 * <p>
69 * When this {@code UnicastSubject} is terminated via {@link #onError(Throwable)} the current or late single {@code Observer}
70 * may receive the {@code Throwable} before any available items could be emitted. To make sure an onError event is delivered
71 * to the {@code Observer} after the normal items, create a {@code UnicastSubject} with the {@link #create(boolean)} or
72 * {@link #create(int, Runnable, boolean)} factory methods.
73 * <p>
74 * Even though {@code UnicastSubject} implements the {@code Observer} interface, calling
75 * {@code onSubscribe} is not required (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.12">Rule 2.12</a>)
76 * if the subject is used as a standalone source. However, calling {@code onSubscribe}
77 * after the {@code UnicastSubject} reached its terminal state will result in the
78 * given {@code Disposable} being disposed immediately.
79 * <p>
80 * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()}
81 * is required to be serialized (called from the same thread or called non-overlappingly from different threads
82 * through external means of serialization). The {@link #toSerialized()} method available to all {@code Subject}s
83 * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Observer}
84 * consuming this subject also wants to call {@link #onNext(Object)} on this subject recursively).
85 * <p>
86 * This {@code UnicastSubject} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()},
87 * {@link #getThrowable()} and {@link #hasObservers()}.
88 * <dl>
89 * <dt><b>Scheduler:</b></dt>
90 * <dd>{@code UnicastSubject} does not operate by default on a particular {@link io.reactivex.rxjava3.core.Scheduler} and
91 * the single {@code Observer} gets notified on the thread the respective {@code onXXX} methods were invoked.</dd>
92 * <dt><b>Error handling:</b></dt>
93 * <dd>When the {@link #onError(Throwable)} is called, the {@code UnicastSubject} enters into a terminal state
94 * and emits the same {@code Throwable} instance to the current single {@code Observer}. During this emission,
95 * if the single {@code Observer}s disposes its respective {@code Disposable}, the
96 * {@code Throwable} is delivered to the global error handler via
97 * {@link io.reactivex.rxjava3.plugins.RxJavaPlugins#onError(Throwable)}.
98 * If there were no {@code Observer}s subscribed to this {@code UnicastSubject} when the {@code onError()}
99 * was called, the global error handler is not invoked.
100 * </dd>
101 * </dl>
102 * <p>
103 * Example usage:
104 * <pre><code>
105 * UnicastSubject&lt;Integer&gt; subject = UnicastSubject.create();
106 *
107 * TestObserver&lt;Integer&gt; to1 = subject.test();
108 *
109 * // fresh UnicastSubjects are empty
110 * to1.assertEmpty();
111 *
112 * TestObserver&lt;Integer&gt; to2 = subject.test();
113 *
114 * // A UnicastSubject only allows one Observer during its lifetime
115 * to2.assertFailure(IllegalStateException.class);
116 *
117 * subject.onNext(1);
118 * to1.assertValue(1);
119 *
120 * subject.onNext(2);
121 * to1.assertValues(1, 2);
122 *
123 * subject.onComplete();
124 * to1.assertResult(1, 2);
125 *
126 * // ----------------------------------------------------
127 *
128 * UnicastSubject&lt;Integer&gt; subject2 = UnicastSubject.create();
129 *
130 * // a UnicastSubject caches events until its single Observer subscribes
131 * subject2.onNext(1);
132 * subject2.onNext(2);
133 * subject2.onComplete();
134 *
135 * TestObserver&lt;Integer&gt; to3 = subject2.test();
136 *
137 * // the cached events are emitted in order
138 * to3.assertResult(1, 2);
139 * </code></pre>
140 * @param <T> the value type received and emitted by this Subject subclass
141 * @since 2.0
142 */
143 public final class UnicastSubject<T> extends Subject<T> {
144 /** The queue that buffers the source events. */
145 final SpscLinkedArrayQueue<T> queue;
146
147 /** The single Observer. */
148 final AtomicReference<Observer<? super T>> downstream;
149
150 /** The optional callback when the Subject gets cancelled or terminates. */
151 final AtomicReference<Runnable> onTerminate;
152
153 /** deliver onNext events before error event. */
154 final boolean delayError;
155
156 /** Indicates the single observer has cancelled. */
157 volatile boolean disposed;
158
159 /** Indicates the source has terminated. */
160 volatile boolean done;
161 /**
162 * The terminal error if not null.
163 * Must be set before writing to done and read after done == true.
164 */
165 Throwable error;
166
167 /** Set to 1 atomically for the first and only Subscriber. */
168 final AtomicBoolean once;
169
170 /** The wip counter and QueueDisposable surface. */
171 final BasicIntQueueDisposable<T> wip;
172
173 boolean enableOperatorFusion;
174
175 /**
176 * Creates an UnicastSubject with an internal buffer capacity hint 16.
177 * @param <T> the value type
178 * @return an UnicastSubject instance
179 */
180 @CheckReturnValue
181 @NonNull
182 public static <T> UnicastSubject<T> create() {
183 return new UnicastSubject<>(bufferSize(), null, true);
184 }
185
186 /**
187 * Creates an UnicastSubject with the given internal buffer capacity hint.
188 * @param <T> the value type
189 * @param capacityHint the hint to size the internal unbounded buffer
190 * @return an UnicastSubject instance
191 * @throws IllegalArgumentException if {@code capacityHint} is non-positive
192 */
193 @CheckReturnValue
194 @NonNull
195 public static <T> UnicastSubject<T> create(int capacityHint) {
196 ObjectHelper.verifyPositive(capacityHint, "capacityHint");
197 return new UnicastSubject<>(capacityHint, null, true);
198 }
199
200 /**
201 * Creates an UnicastSubject with the given internal buffer capacity hint and a callback for
202 * the case when the single Subscriber cancels its subscription
203 * or the subject is terminated.
204 *
205 * <p>The callback, if not null, is called exactly once and
206 * non-overlapped with any active replay.
207 *
208 * @param <T> the value type
209 * @param capacityHint the hint to size the internal unbounded buffer
210 * @param onTerminate the callback to run when the Subject is terminated or cancelled, null not allowed
211 * @return an UnicastSubject instance
212 * @throws NullPointerException if {@code onTerminate} is {@code null}
213 * @throws IllegalArgumentException if {@code capacityHint} is non-positive
214 */
215 @CheckReturnValue
216 @NonNull
217 public static <T> UnicastSubject<T> create(int capacityHint, @NonNull Runnable onTerminate) {
218 ObjectHelper.verifyPositive(capacityHint, "capacityHint");
219 Objects.requireNonNull(onTerminate, "onTerminate");
220 return new UnicastSubject<>(capacityHint, onTerminate, true);
221 }
222
223 /**
224 * Creates an UnicastSubject with the given internal buffer capacity hint, delay error flag and
225 * a callback for the case when the single Observer disposes its {@link Disposable}
226 * or the subject is terminated.
227 *
228 * <p>The callback, if not null, is called exactly once and
229 * non-overlapped with any active replay.
230 * <p>History: 2.0.8 - experimental
231 * @param <T> the value type
232 * @param capacityHint the hint to size the internal unbounded buffer
233 * @param onTerminate the callback to run when the Subject is terminated or cancelled, null not allowed
234 * @param delayError deliver pending onNext events before onError
235 * @return an UnicastSubject instance
236 * @throws NullPointerException if {@code onTerminate} is {@code null}
237 * @throws IllegalArgumentException if {@code capacityHint} is non-positive
238 * @since 2.2
239 */
240 @CheckReturnValue
241 @NonNull
242 public static <T> UnicastSubject<T> create(int capacityHint, @NonNull Runnable onTerminate, boolean delayError) {
243 ObjectHelper.verifyPositive(capacityHint, "capacityHint");
244 Objects.requireNonNull(onTerminate, "onTerminate");
245 return new UnicastSubject<>(capacityHint, onTerminate, delayError);
246 }
247
248 /**
249 * Creates an UnicastSubject with an internal buffer capacity hint 16 and given delay error flag.
250 *
251 * <p>The callback, if not null, is called exactly once and
252 * non-overlapped with any active replay.
253 * <p>History: 2.0.8 - experimental
254 * @param <T> the value type
255 * @param delayError deliver pending onNext events before onError
256 * @return an UnicastSubject instance
257 * @since 2.2
258 */
259 @CheckReturnValue
260 @NonNull
261 public static <T> UnicastSubject<T> create(boolean delayError) {
262 return new UnicastSubject<>(bufferSize(), null, delayError);
263 }
264
265 /**
266 * Creates an UnicastSubject with the given capacity hint, delay error flag and callback
267 * for when the Subject is terminated normally or its single Subscriber cancels.
268 * <p>History: 2.0.8 - experimental
269 * @param capacityHint the capacity hint for the internal, unbounded queue
270 * @param onTerminate the callback to run when the Subject is terminated or cancelled, null not allowed
271 * @param delayError deliver pending onNext events before onError
272 * @since 2.2
273 */
274 UnicastSubject(int capacityHint, Runnable onTerminate, boolean delayError) {
275 this.queue = new SpscLinkedArrayQueue<>(capacityHint);
276 this.onTerminate = new AtomicReference<>(onTerminate);
277 this.delayError = delayError;
278 this.downstream = new AtomicReference<>();
279 this.once = new AtomicBoolean();
280 this.wip = new UnicastQueueDisposable();
281 }
282
283 @Override
284 protected void subscribeActual(Observer<? super T> observer) {
285 if (!once.get() && once.compareAndSet(false, true)) {
286 observer.onSubscribe(wip);
287 downstream.lazySet(observer); // full barrier in drain
288 if (disposed) {
289 downstream.lazySet(null);
290 return;
291 }
292 drain();
293 } else {
294 EmptyDisposable.error(new IllegalStateException("Only a single observer allowed."), observer);
295 }
296 }
297
298 void doTerminate() {
299 Runnable r = onTerminate.get();
300 if (r != null && onTerminate.compareAndSet(r, null)) {
301 r.run();
302 }
303 }
304
305 @Override
306 public void onSubscribe(Disposable d) {
307 if (done || disposed) {
308 d.dispose();
309 }
310 }
311
312 @Override
313 public void onNext(T t) {
314 ExceptionHelper.nullCheck(t, "onNext called with a null value.");
315 if (done || disposed) {
316 return;
317 }
318 queue.offer(t);
319 drain();
320 }
321
322 @Override
323 public void onError(Throwable t) {
324 ExceptionHelper.nullCheck(t, "onError called with a null Throwable.");
325 if (done || disposed) {
326 RxJavaPlugins.onError(t);
327 return;
328 }
329 error = t;
330 done = true;
331
332 doTerminate();
333
334 drain();
335 }
336
337 @Override
338 public void onComplete() {
339 if (done || disposed) {
340 return;
341 }
342 done = true;
343
344 doTerminate();
345
346 drain();
347 }
348
349 void drainNormal(Observer<? super T> a) {
350 int missed = 1;
351 SimpleQueue<T> q = queue;
352 boolean failFast = !this.delayError;
353 boolean canBeError = true;
354 for (;;) {
355 for (;;) {
356
357 if (disposed) {
358 downstream.lazySet(null);
359 q.clear();
360 return;
361 }
362
363 boolean d = this.done;
364 T v = queue.poll();
365 boolean empty = v == null;
366
367 if (d) {
368 if (failFast && canBeError) {
369 if (failedFast(q, a)) {
370 return;
371 } else {
372 canBeError = false;
373 }
374 }
375
376 if (empty) {
377 errorOrComplete(a);
378 return;
379 }
380 }
381
382 if (empty) {
383 break;
384 }
385
386 a.onNext(v);
387 }
388
389 missed = wip.addAndGet(-missed);
390 if (missed == 0) {
391 break;
392 }
393 }
394 }
395
396 void drainFused(Observer<? super T> a) {
397 int missed = 1;
398
399 final SpscLinkedArrayQueue<T> q = queue;
400 final boolean failFast = !delayError;
401
402 for (;;) {
403
404 if (disposed) {
405 downstream.lazySet(null);
406 return;
407 }
408 boolean d = done;
409
410 if (failFast && d) {
411 if (failedFast(q, a)) {
412 return;
413 }
414 }
415
416 a.onNext(null);
417
418 if (d) {
419 errorOrComplete(a);
420 return;
421 }
422
423 missed = wip.addAndGet(-missed);
424 if (missed == 0) {
425 break;
426 }
427 }
428 }
429
430 void errorOrComplete(Observer<? super T> a) {
431 downstream.lazySet(null);
432 Throwable ex = error;
433 if (ex != null) {
434 a.onError(ex);
435 } else {
436 a.onComplete();
437 }
438 }
439
440 boolean failedFast(final SimpleQueue<T> q, Observer<? super T> a) {
441 Throwable ex = error;
442 if (ex != null) {
443 downstream.lazySet(null);
444 q.clear();
445 a.onError(ex);
446 return true;
447 } else {
448 return false;
449 }
450 }
451
452 void drain() {
453 if (wip.getAndIncrement() != 0) {
454 return;
455 }
456
457 Observer<? super T> a = downstream.get();
458 int missed = 1;
459
460 for (;;) {
461
462 if (a != null) {
463 if (enableOperatorFusion) {
464 drainFused(a);
465 } else {
466 drainNormal(a);
467 }
468 return;
469 }
470
471 missed = wip.addAndGet(-missed);
472 if (missed == 0) {
473 break;
474 }
475
476 a = downstream.get();
477 }
478 }
479
480 @Override
481 @CheckReturnValue
482 public boolean hasObservers() {
483 return downstream.get() != null;
484 }
485
486 @Override
487 @Nullable
488 @CheckReturnValue
489 public Throwable getThrowable() {
490 if (done) {
491 return error;
492 }
493 return null;
494 }
495
496 @Override
497 @CheckReturnValue
498 public boolean hasThrowable() {
499 return done && error != null;
500 }
501
502 @Override
503 @CheckReturnValue
504 public boolean hasComplete() {
505 return done && error == null;
506 }
507
508 final class UnicastQueueDisposable extends BasicIntQueueDisposable<T> {
509
510 private static final long serialVersionUID = 7926949470189395511L;
511
512 @Override
513 public int requestFusion(int mode) {
514 if ((mode & ASYNC) != 0) {
515 enableOperatorFusion = true;
516 return ASYNC;
517 }
518 return NONE;
519 }
520
521 @Nullable
522 @Override
523 public T poll() {
524 return queue.poll();
525 }
526
527 @Override
528 public boolean isEmpty() {
529 return queue.isEmpty();
530 }
531
532 @Override
533 public void clear() {
534 queue.clear();
535 }
536
537 @Override
538 public void dispose() {
539 if (!disposed) {
540 disposed = true;
541
542 doTerminate();
543
544 downstream.lazySet(null);
545 if (wip.getAndIncrement() == 0) {
546 downstream.lazySet(null);
547 if (!enableOperatorFusion) {
548 queue.clear();
549 }
550 }
551 }
552 }
553
554 @Override
555 public boolean isDisposed() {
556 return disposed;
557 }
558
559 }
560 }