Debian Codegraph @

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