Debian Codegraph @

src/main/java/io/reactivex/rxjava3/subjects/BehaviorSubject.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.AtomicReference;
18 import java.util.concurrent.locks.*;
19
20 import io.reactivex.rxjava3.annotations.*;
21 import io.reactivex.rxjava3.core.Observer;
22 import io.reactivex.rxjava3.disposables.Disposable;
23 import io.reactivex.rxjava3.internal.util.*;
24 import io.reactivex.rxjava3.internal.util.AppendOnlyLinkedArrayList.NonThrowingPredicate;
25 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
26
27 /**
28 * Subject that emits the most recent item it has observed and all subsequent observed items to each subscribed
29 * {@link Observer}.
30 * <p>
31 * <img width="640" height="415" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/S.BehaviorSubject.v3.png" alt="">
32 * <p>
33 * This subject does not have a public constructor by design; a new empty instance of this
34 * {@code BehaviorSubject} can be created via the {@link #create()} method and
35 * a new non-empty instance can be created via {@link #createDefault(Object)} (named as such to avoid
36 * overload resolution conflict with {@code Observable.create} that creates an Observable, not a {@code BehaviorSubject}).
37 * <p>
38 * Since a {@code Subject} is conceptionally derived from the {@code Processor} type in the Reactive Streams specification,
39 * {@code null}s are not allowed (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.13">Rule 2.13</a>) as
40 * default initial values in {@link #createDefault(Object)} or as parameters to {@link #onNext(Object)} and
41 * {@link #onError(Throwable)}. Such calls will result in a
42 * {@link NullPointerException} being thrown and the subject's state is not changed.
43 * <p>
44 * Since a {@code BehaviorSubject} is an {@link io.reactivex.rxjava3.core.Observable}, it does not support backpressure.
45 * <p>
46 * When this {@code BehaviorSubject} is terminated via {@link #onError(Throwable)} or {@link #onComplete()}, the
47 * last observed item (if any) is cleared and late {@link io.reactivex.rxjava3.core.Observer}s only receive
48 * the respective terminal event.
49 * <p>
50 * The {@code BehaviorSubject} does not support clearing its cached value (to appear empty again), however, the
51 * effect can be achieved by using a special item and making sure {@code Observer}s subscribe through a
52 * filter whose predicate filters out this special item:
53 * <pre><code>
54 * BehaviorSubject&lt;Integer&gt; subject = BehaviorSubject.create();
55 *
56 * final Integer EMPTY = Integer.MIN_VALUE;
57 *
58 * Observable&lt;Integer&gt; observable = subject.filter(v -&gt; v != EMPTY);
59 *
60 * TestObserver&lt;Integer&gt; to1 = observable.test();
61 *
62 * observable.onNext(1);
63 * // this will "clear" the cache
64 * observable.onNext(EMPTY);
65 *
66 * TestObserver&lt;Integer&gt; to2 = observable.test();
67 *
68 * subject.onNext(2);
69 * subject.onComplete();
70 *
71 * // to1 received both non-empty items
72 * to1.assertResult(1, 2);
73 *
74 * // to2 received only 2 even though the current item was EMPTY
75 * // when it got subscribed
76 * to2.assertResult(2);
77 *
78 * // Observers coming after the subject was terminated receive
79 * // no items and only the onComplete event in this case.
80 * observable.test().assertResult();
81 * </code></pre>
82 * <p>
83 * Even though {@code BehaviorSubject} implements the {@code Observer} interface, calling
84 * {@code onSubscribe} is not required (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.12">Rule 2.12</a>)
85 * if the subject is used as a standalone source. However, calling {@code onSubscribe}
86 * after the {@code BehaviorSubject} reached its terminal state will result in the
87 * given {@code Disposable} being disposed immediately.
88 * <p>
89 * Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()}
90 * is required to be serialized (called from the same thread or called non-overlappingly from different threads
91 * through external means of serialization). The {@link #toSerialized()} method available to all {@code Subject}s
92 * provides such serialization and also protects against reentrance (i.e., when a downstream {@code Observer}
93 * consuming this subject also wants to call {@link #onNext(Object)} on this subject recursively).
94 * <p>
95 * This {@code BehaviorSubject} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()},
96 * {@link #getThrowable()} and {@link #hasObservers()} as well as means to read the latest observed value
97 * in a non-blocking and thread-safe manner via {@link #hasValue()} or {@link #getValue()}.
98 * <dl>
99 * <dt><b>Scheduler:</b></dt>
100 * <dd>{@code BehaviorSubject} does not operate by default on a particular {@link io.reactivex.rxjava3.core.Scheduler} and
101 * the {@code Observer}s get notified on the thread the respective {@code onXXX} methods were invoked.</dd>
102 * <dt><b>Error handling:</b></dt>
103 * <dd>When the {@link #onError(Throwable)} is called, the {@code BehaviorSubject} enters into a terminal state
104 * and emits the same {@code Throwable} instance to the last set of {@code Observer}s. During this emission,
105 * if one or more {@code Observer}s dispose their respective {@code Disposable}s, the
106 * {@code Throwable} is delivered to the global error handler via
107 * {@link io.reactivex.rxjava3.plugins.RxJavaPlugins#onError(Throwable)} (multiple times if multiple {@code Observer}s
108 * cancel at once).
109 * If there were no {@code Observer}s subscribed to this {@code BehaviorSubject} when the {@code onError()}
110 * was called, the global error handler is not invoked.
111 * </dd>
112 * </dl>
113 * <p>
114 * Example usage:
115 * <pre> {@code
116
117 // observer will receive all 4 events (including "default").
118 BehaviorSubject<Object> subject = BehaviorSubject.createDefault("default");
119 subject.subscribe(observer);
120 subject.onNext("one");
121 subject.onNext("two");
122 subject.onNext("three");
123
124 // observer will receive the "one", "two" and "three" events, but not "zero"
125 BehaviorSubject<Object> subject = BehaviorSubject.create();
126 subject.onNext("zero");
127 subject.onNext("one");
128 subject.subscribe(observer);
129 subject.onNext("two");
130 subject.onNext("three");
131
132 // observer will receive only onComplete
133 BehaviorSubject<Object> subject = BehaviorSubject.create();
134 subject.onNext("zero");
135 subject.onNext("one");
136 subject.onComplete();
137 subject.subscribe(observer);
138
139 // observer will receive only onError
140 BehaviorSubject<Object> subject = BehaviorSubject.create();
141 subject.onNext("zero");
142 subject.onNext("one");
143 subject.onError(new RuntimeException("error"));
144 subject.subscribe(observer);
145 } </pre>
146 *
147 * @param <T>
148 * the type of item expected to be observed by the Subject
149 */
150 public final class BehaviorSubject<T> extends Subject<T> {
151
152 final AtomicReference<Object> value;
153
154 final AtomicReference<BehaviorDisposable<T>[]> observers;
155
156 @SuppressWarnings("rawtypes")
157 static final BehaviorDisposable[] EMPTY = new BehaviorDisposable[0];
158
159 @SuppressWarnings("rawtypes")
160 static final BehaviorDisposable[] TERMINATED = new BehaviorDisposable[0];
161 final ReadWriteLock lock;
162 final Lock readLock;
163 final Lock writeLock;
164
165 final AtomicReference<Throwable> terminalEvent;
166
167 long index;
168
169 /**
170 * Creates a {@link BehaviorSubject} without a default item.
171 *
172 * @param <T>
173 * the type of item the Subject will emit
174 * @return the constructed {@link BehaviorSubject}
175 */
176 @CheckReturnValue
177 @NonNull
178 public static <T> BehaviorSubject<T> create() {
179 return new BehaviorSubject<>(null);
180 }
181
182 /**
183 * Creates a {@link BehaviorSubject} that emits the last item it observed and all subsequent items to each
184 * {@link Observer} that subscribes to it.
185 *
186 * @param <T>
187 * the type of item the Subject will emit
188 * @param defaultValue
189 * the item that will be emitted first to any {@link Observer} as long as the
190 * {@link BehaviorSubject} has not yet observed any items from its source {@code Observable}
191 * @return the constructed {@link BehaviorSubject}
192 * @throws NullPointerException if {@code defaultValue} is {@code null}
193 */
194 @CheckReturnValue
195 @NonNull
196 public static <@NonNull T> BehaviorSubject<T> createDefault(T defaultValue) {
197 Objects.requireNonNull(defaultValue, "defaultValue is null");
198 return new BehaviorSubject<>(defaultValue);
199 }
200
201 /**
202 * Constructs an empty BehaviorSubject.
203 * @param defaultValue the initial value, not null (verified)
204 * @since 2.0
205 */
206 @SuppressWarnings("unchecked")
207 BehaviorSubject(T defaultValue) {
208 this.lock = new ReentrantReadWriteLock();
209 this.readLock = lock.readLock();
210 this.writeLock = lock.writeLock();
211 this.observers = new AtomicReference<>(EMPTY);
212 this.value = new AtomicReference<>(defaultValue);
213 this.terminalEvent = new AtomicReference<>();
214 }
215
216 @Override
217 protected void subscribeActual(Observer<? super T> observer) {
218 BehaviorDisposable<T> bs = new BehaviorDisposable<>(observer, this);
219 observer.onSubscribe(bs);
220 if (add(bs)) {
221 if (bs.cancelled) {
222 remove(bs);
223 } else {
224 bs.emitFirst();
225 }
226 } else {
227 Throwable ex = terminalEvent.get();
228 if (ex == ExceptionHelper.TERMINATED) {
229 observer.onComplete();
230 } else {
231 observer.onError(ex);
232 }
233 }
234 }
235
236 @Override
237 public void onSubscribe(Disposable d) {
238 if (terminalEvent.get() != null) {
239 d.dispose();
240 }
241 }
242
243 @Override
244 public void onNext(T t) {
245 ExceptionHelper.nullCheck(t, "onNext called with a null value.");
246
247 if (terminalEvent.get() != null) {
248 return;
249 }
250 Object o = NotificationLite.next(t);
251 setCurrent(o);
252 for (BehaviorDisposable<T> bs : observers.get()) {
253 bs.emitNext(o, index);
254 }
255 }
256
257 @Override
258 public void onError(Throwable t) {
259 ExceptionHelper.nullCheck(t, "onError called with a null Throwable.");
260 if (!terminalEvent.compareAndSet(null, t)) {
261 RxJavaPlugins.onError(t);
262 return;
263 }
264 Object o = NotificationLite.error(t);
265 for (BehaviorDisposable<T> bs : terminate(o)) {
266 bs.emitNext(o, index);
267 }
268 }
269
270 @Override
271 public void onComplete() {
272 if (!terminalEvent.compareAndSet(null, ExceptionHelper.TERMINATED)) {
273 return;
274 }
275 Object o = NotificationLite.complete();
276 for (BehaviorDisposable<T> bs : terminate(o)) {
277 bs.emitNext(o, index); // relaxed read okay since this is the only mutator thread
278 }
279 }
280
281 @Override
282 @CheckReturnValue
283 public boolean hasObservers() {
284 return observers.get().length != 0;
285 }
286
287 @CheckReturnValue
288 /* test support*/ int subscriberCount() {
289 return observers.get().length;
290 }
291
292 @Override
293 @Nullable
294 @CheckReturnValue
295 public Throwable getThrowable() {
296 Object o = value.get();
297 if (NotificationLite.isError(o)) {
298 return NotificationLite.getError(o);
299 }
300 return null;
301 }
302
303 /**
304 * Returns a single value the Subject currently has or null if no such value exists.
305 * <p>The method is thread-safe.
306 * @return a single value the Subject currently has or null if no such value exists
307 */
308 @Nullable
309 @CheckReturnValue
310 public T getValue() {
311 Object o = value.get();
312 if (NotificationLite.isComplete(o) || NotificationLite.isError(o)) {
313 return null;
314 }
315 return NotificationLite.getValue(o);
316 }
317
318 @Override
319 @CheckReturnValue
320 public boolean hasComplete() {
321 Object o = value.get();
322 return NotificationLite.isComplete(o);
323 }
324
325 @Override
326 @CheckReturnValue
327 public boolean hasThrowable() {
328 Object o = value.get();
329 return NotificationLite.isError(o);
330 }
331
332 /**
333 * Returns true if the subject has any value.
334 * <p>The method is thread-safe.
335 * @return true if the subject has any value
336 */
337 @CheckReturnValue
338 public boolean hasValue() {
339 Object o = value.get();
340 return o != null && !NotificationLite.isComplete(o) && !NotificationLite.isError(o);
341 }
342
343 boolean add(BehaviorDisposable<T> rs) {
344 for (;;) {
345 BehaviorDisposable<T>[] a = observers.get();
346 if (a == TERMINATED) {
347 return false;
348 }
349 int len = a.length;
350 @SuppressWarnings("unchecked")
351 BehaviorDisposable<T>[] b = new BehaviorDisposable[len + 1];
352 System.arraycopy(a, 0, b, 0, len);
353 b[len] = rs;
354 if (observers.compareAndSet(a, b)) {
355 return true;
356 }
357 }
358 }
359
360 @SuppressWarnings("unchecked")
361 void remove(BehaviorDisposable<T> rs) {
362 for (;;) {
363 BehaviorDisposable<T>[] a = observers.get();
364 int len = a.length;
365 if (len == 0) {
366 return;
367 }
368 int j = -1;
369 for (int i = 0; i < len; i++) {
370 if (a[i] == rs) {
371 j = i;
372 break;
373 }
374 }
375
376 if (j < 0) {
377 return;
378 }
379 BehaviorDisposable<T>[] b;
380 if (len == 1) {
381 b = EMPTY;
382 } else {
383 b = new BehaviorDisposable[len - 1];
384 System.arraycopy(a, 0, b, 0, j);
385 System.arraycopy(a, j + 1, b, j, len - j - 1);
386 }
387 if (observers.compareAndSet(a, b)) {
388 return;
389 }
390 }
391 }
392
393 @SuppressWarnings("unchecked")
394 BehaviorDisposable<T>[] terminate(Object terminalValue) {
395
396 setCurrent(terminalValue);
397
398 return observers.getAndSet(TERMINATED);
399 }
400
401 void setCurrent(Object o) {
402 writeLock.lock();
403 index++;
404 value.lazySet(o);
405 writeLock.unlock();
406 }
407
408 static final class BehaviorDisposable<T> implements Disposable, NonThrowingPredicate<Object> {
409
410 final Observer<? super T> downstream;
411 final BehaviorSubject<T> state;
412
413 boolean next;
414 boolean emitting;
415 AppendOnlyLinkedArrayList<Object> queue;
416
417 boolean fastPath;
418
419 volatile boolean cancelled;
420
421 long index;
422
423 BehaviorDisposable(Observer<? super T> actual, BehaviorSubject<T> state) {
424 this.downstream = actual;
425 this.state = state;
426 }
427
428 @Override
429 public void dispose() {
430 if (!cancelled) {
431 cancelled = true;
432
433 state.remove(this);
434 }
435 }
436
437 @Override
438 public boolean isDisposed() {
439 return cancelled;
440 }
441
442 void emitFirst() {
443 if (cancelled) {
444 return;
445 }
446 Object o;
447 synchronized (this) {
448 if (cancelled) {
449 return;
450 }
451 if (next) {
452 return;
453 }
454
455 BehaviorSubject<T> s = state;
456 Lock lock = s.readLock;
457
458 lock.lock();
459 index = s.index;
460 o = s.value.get();
461 lock.unlock();
462
463 emitting = o != null;
464 next = true;
465 }
466
467 if (o != null) {
468 if (test(o)) {
469 return;
470 }
471
472 emitLoop();
473 }
474 }
475
476 void emitNext(Object value, long stateIndex) {
477 if (cancelled) {
478 return;
479 }
480 if (!fastPath) {
481 synchronized (this) {
482 if (cancelled) {
483 return;
484 }
485 if (index == stateIndex) {
486 return;
487 }
488 if (emitting) {
489 AppendOnlyLinkedArrayList<Object> q = queue;
490 if (q == null) {
491 q = new AppendOnlyLinkedArrayList<>(4);
492 queue = q;
493 }
494 q.add(value);
495 return;
496 }
497 next = true;
498 }
499 fastPath = true;
500 }
501
502 test(value);
503 }
504
505 @Override
506 public boolean test(Object o) {
507 return cancelled || NotificationLite.accept(o, downstream);
508 }
509
510 void emitLoop() {
511 for (;;) {
512 if (cancelled) {
513 return;
514 }
515 AppendOnlyLinkedArrayList<Object> q;
516 synchronized (this) {
517 q = queue;
518 if (q == null) {
519 emitting = false;
520 return;
521 }
522 queue = null;
523 }
524
525 q.forEachWhile(this);
526 }
527 }
528 }
529 }