Debian Codegraph @

src/main/java/io/reactivex/rxjava3/subjects/SingleSubject.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.*;
17
18 import io.reactivex.rxjava3.annotations.*;
19 import io.reactivex.rxjava3.core.*;
20 import io.reactivex.rxjava3.disposables.Disposable;
21 import io.reactivex.rxjava3.internal.util.ExceptionHelper;
22 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
23
24 /**
25 * Represents a hot Single-like source and consumer of events similar to Subjects.
26 * <p>
27 * <img width="640" height="236" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/SingleSubject.png" alt="">
28 * <p>
29 * This subject does not have a public constructor by design; a new non-terminated instance of this
30 * {@code SingleSubject} can be created via the {@link #create()} method.
31 * <p>
32 * Since the {@code SingleSubject} is conceptionally derived from the {@code Processor} type in the Reactive Streams specification,
33 * {@code null}s are not allowed (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.13">Rule 2.13</a>)
34 * as parameters to {@link #onSuccess(Object)} and {@link #onError(Throwable)}. Such calls will result in a
35 * {@link NullPointerException} being thrown and the subject's state is not changed.
36 * <p>
37 * Since a {@code SingleSubject} is a {@link io.reactivex.rxjava3.core.Single}, calling {@code onSuccess} or {@code onError}
38 * will move this {@code SingleSubject} into its terminal state atomically.
39 * <p>
40 * All methods are thread safe. Calling {@link #onSuccess(Object)} multiple
41 * times has no effect. Calling {@link #onError(Throwable)} multiple times relays the {@code Throwable} to
42 * the {@link io.reactivex.rxjava3.plugins.RxJavaPlugins#onError(Throwable)} global error handler.
43 * <p>
44 * Even though {@code SingleSubject} implements the {@code SingleObserver} interface, calling
45 * {@code onSubscribe} is not required (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.12">Rule 2.12</a>)
46 * if the subject is used as a standalone source. However, calling {@code onSubscribe}
47 * after the {@code SingleSubject} reached its terminal state will result in the
48 * given {@code Disposable} being disposed immediately.
49 * <p>
50 * This {@code SingleSubject} supports the standard state-peeking methods {@link #hasThrowable()},
51 * {@link #getThrowable()} and {@link #hasObservers()} as well as means to read any success item in a non-blocking
52 * and thread-safe manner via {@link #hasValue()} and {@link #getValue()}.
53 * <p>
54 * The {@code SingleSubject} does not support clearing its cached {@code onSuccess} value.
55 * <dl>
56 * <dt><b>Scheduler:</b></dt>
57 * <dd>{@code SingleSubject} does not operate by default on a particular {@link io.reactivex.rxjava3.core.Scheduler} and
58 * the {@code SingleObserver}s get notified on the thread where the terminating {@code onSuccess} or {@code onError}
59 * methods were invoked.</dd>
60 * <dt><b>Error handling:</b></dt>
61 * <dd>When the {@link #onError(Throwable)} is called, the {@code SingleSubject} enters into a terminal state
62 * and emits the same {@code Throwable} instance to the last set of {@code SingleObserver}s. During this emission,
63 * if one or more {@code SingleObserver}s dispose their respective {@code Disposable}s, the
64 * {@code Throwable} is delivered to the global error handler via
65 * {@link io.reactivex.rxjava3.plugins.RxJavaPlugins#onError(Throwable)} (multiple times if multiple {@code SingleObserver}s
66 * cancel at once).
67 * If there were no {@code SingleObserver}s subscribed to this {@code SingleSubject} when the {@code onError()}
68 * was called, the global error handler is not invoked.
69 * </dd>
70 * </dl>
71 * <p>
72 * Example usage:
73 * <pre><code>
74 * SingleSubject&lt;Integer&gt; subject1 = SingleSubject.create();
75 *
76 * TestObserver&lt;Integer&gt; to1 = subject1.test();
77 *
78 * // SingleSubjects are empty by default
79 * to1.assertEmpty();
80 *
81 * subject1.onSuccess(1);
82 *
83 * // onSuccess is a terminal event with SingleSubjects
84 * // TestObserver converts onSuccess into onNext + onComplete
85 * to1.assertResult(1);
86 *
87 * TestObserver&lt;Integer&gt; to2 = subject1.test();
88 *
89 * // late Observers receive the terminal signal (onSuccess) too
90 * to2.assertResult(1);
91 * </code></pre>
92 * <p>History: 2.0.5 - experimental
93 * @param <T> the value type received and emitted
94 * @since 2.1
95 */
96 public final class SingleSubject<T> extends Single<T> implements SingleObserver<T> {
97
98 final AtomicReference<SingleDisposable<T>[]> observers;
99
100 @SuppressWarnings("rawtypes")
101 static final SingleDisposable[] EMPTY = new SingleDisposable[0];
102
103 @SuppressWarnings("rawtypes")
104 static final SingleDisposable[] TERMINATED = new SingleDisposable[0];
105
106 final AtomicBoolean once;
107 T value;
108 Throwable error;
109
110 /**
111 * Creates a fresh SingleSubject.
112 * @param <T> the value type received and emitted
113 * @return the new SingleSubject instance
114 */
115 @CheckReturnValue
116 @NonNull
117 public static <T> SingleSubject<T> create() {
118 return new SingleSubject<>();
119 }
120
121 @SuppressWarnings("unchecked")
122 SingleSubject() {
123 once = new AtomicBoolean();
124 observers = new AtomicReference<>(EMPTY);
125 }
126
127 @Override
128 public void onSubscribe(@NonNull Disposable d) {
129 if (observers.get() == TERMINATED) {
130 d.dispose();
131 }
132 }
133
134 @SuppressWarnings("unchecked")
135 @Override
136 public void onSuccess(@NonNull T value) {
137 ExceptionHelper.nullCheck(value, "onSuccess called with a null value.");
138 if (once.compareAndSet(false, true)) {
139 this.value = value;
140 for (SingleDisposable<T> md : observers.getAndSet(TERMINATED)) {
141 md.downstream.onSuccess(value);
142 }
143 }
144 }
145
146 @SuppressWarnings("unchecked")
147 @Override
148 public void onError(@NonNull Throwable e) {
149 ExceptionHelper.nullCheck(e, "onError called with a null Throwable.");
150 if (once.compareAndSet(false, true)) {
151 this.error = e;
152 for (SingleDisposable<T> md : observers.getAndSet(TERMINATED)) {
153 md.downstream.onError(e);
154 }
155 } else {
156 RxJavaPlugins.onError(e);
157 }
158 }
159
160 @Override
161 protected void subscribeActual(@NonNull SingleObserver<? super T> observer) {
162 SingleDisposable<T> md = new SingleDisposable<>(observer, this);
163 observer.onSubscribe(md);
164 if (add(md)) {
165 if (md.isDisposed()) {
166 remove(md);
167 }
168 } else {
169 Throwable ex = error;
170 if (ex != null) {
171 observer.onError(ex);
172 } else {
173 observer.onSuccess(value);
174 }
175 }
176 }
177
178 boolean add(@NonNull SingleDisposable<T> inner) {
179 for (;;) {
180 SingleDisposable<T>[] a = observers.get();
181 if (a == TERMINATED) {
182 return false;
183 }
184
185 int n = a.length;
186 @SuppressWarnings("unchecked")
187 SingleDisposable<T>[] b = new SingleDisposable[n + 1];
188 System.arraycopy(a, 0, b, 0, n);
189 b[n] = inner;
190 if (observers.compareAndSet(a, b)) {
191 return true;
192 }
193 }
194 }
195
196 @SuppressWarnings("unchecked")
197 void remove(@NonNull SingleDisposable<T> inner) {
198 for (;;) {
199 SingleDisposable<T>[] a = observers.get();
200 int n = a.length;
201 if (n == 0) {
202 return;
203 }
204
205 int j = -1;
206
207 for (int i = 0; i < n; i++) {
208 if (a[i] == inner) {
209 j = i;
210 break;
211 }
212 }
213
214 if (j < 0) {
215 return;
216 }
217 SingleDisposable<T>[] b;
218 if (n == 1) {
219 b = EMPTY;
220 } else {
221 b = new SingleDisposable[n - 1];
222 System.arraycopy(a, 0, b, 0, j);
223 System.arraycopy(a, j + 1, b, j, n - j - 1);
224 }
225
226 if (observers.compareAndSet(a, b)) {
227 return;
228 }
229 }
230 }
231
232 /**
233 * Returns the success value if this SingleSubject was terminated with a success value.
234 * @return the success value or null
235 */
236 @Nullable
237 public T getValue() {
238 if (observers.get() == TERMINATED) {
239 return value;
240 }
241 return null;
242 }
243
244 /**
245 * Returns true if this SingleSubject was terminated with a success value.
246 * @return true if this SingleSubject was terminated with a success value
247 */
248 public boolean hasValue() {
249 return observers.get() == TERMINATED && value != null;
250 }
251
252 /**
253 * Returns the terminal error if this SingleSubject has been terminated with an error, null otherwise.
254 * @return the terminal error or null if not terminated or not with an error
255 */
256 @Nullable
257 public Throwable getThrowable() {
258 if (observers.get() == TERMINATED) {
259 return error;
260 }
261 return null;
262 }
263
264 /**
265 * Returns true if this SingleSubject has been terminated with an error.
266 * @return true if this SingleSubject has been terminated with an error
267 */
268 public boolean hasThrowable() {
269 return observers.get() == TERMINATED && error != null;
270 }
271
272 /**
273 * Returns true if this SingleSubject has observers.
274 * @return true if this SingleSubject has observers
275 */
276 public boolean hasObservers() {
277 return observers.get().length != 0;
278 }
279
280 /**
281 * Returns the number of current observers.
282 * @return the number of current observers
283 */
284 /* test */ int observerCount() {
285 return observers.get().length;
286 }
287
288 static final class SingleDisposable<T>
289 extends AtomicReference<SingleSubject<T>> implements Disposable {
290 private static final long serialVersionUID = -7650903191002190468L;
291
292 final SingleObserver<? super T> downstream;
293
294 SingleDisposable(SingleObserver<? super T> actual, SingleSubject<T> parent) {
295 this.downstream = actual;
296 lazySet(parent);
297 }
298
299 @Override
300 public void dispose() {
301 SingleSubject<T> parent = getAndSet(null);
302 if (parent != null) {
303 parent.remove(this);
304 }
305 }
306
307 @Override
308 public boolean isDisposed() {
309 return get() == null;
310 }
311 }
312 }