Debian Codegraph @

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