| 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.Observer; |
| 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 |
* A Subject that emits (multicasts) items to currently subscribed {@link Observer}s and terminal events to current |
| 26 |
* or late {@code Observer}s. |
| 27 |
* <p> |
| 28 |
* <img width="640" height="281" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/PublishSubject.png" alt=""> |
| 29 |
* <p> |
| 30 |
* This subject does not have a public constructor by design; a new empty instance of this |
| 31 |
* {@code PublishSubject} 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>) as |
| 35 |
* 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 a {@code PublishSubject} is an {@link io.reactivex.rxjava3.core.Observable}, it does not support backpressure. |
| 39 |
* <p> |
| 40 |
* When this {@code PublishSubject} is terminated via {@link #onError(Throwable)} or {@link #onComplete()}, |
| 41 |
* late {@link io.reactivex.rxjava3.core.Observer}s only receive the respective terminal event. |
| 42 |
* <p> |
| 43 |
* Unlike a {@link BehaviorSubject}, a {@code PublishSubject} doesn't retain/cache items, therefore, a new |
| 44 |
* {@code Observer} won't receive any past items. |
| 45 |
* <p> |
| 46 |
* Even though {@code PublishSubject} implements the {@code Observer} interface, calling |
| 47 |
* {@code onSubscribe} is not required (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.12">Rule 2.12</a>) |
| 48 |
* if the subject is used as a standalone source. However, calling {@code onSubscribe} |
| 49 |
* after the {@code PublishSubject} reached its terminal state will result in the |
| 50 |
* given {@code Disposable} being disposed immediately. |
| 51 |
* <p> |
| 52 |
* Calling {@link #onNext(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} |
| 53 |
* is required to be serialized (called from the same thread or called non-overlappingly from different threads |
| 54 |
* through external means of serialization). The {@link #toSerialized()} method available to all {@code Subject}s |
| 55 |
* provides such serialization and also protects against reentrance (i.e., when a downstream {@code Observer} |
| 56 |
* consuming this subject also wants to call {@link #onNext(Object)} on this subject recursively). |
| 57 |
* <p> |
| 58 |
* This {@code PublishSubject} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()}, |
| 59 |
* {@link #getThrowable()} and {@link #hasObservers()}. |
| 60 |
* <dl> |
| 61 |
* <dt><b>Scheduler:</b></dt> |
| 62 |
* <dd>{@code PublishSubject} does not operate by default on a particular {@link io.reactivex.rxjava3.core.Scheduler} and |
| 63 |
* the {@code Observer}s get notified on the thread the respective {@code onXXX} methods were invoked.</dd> |
| 64 |
* <dt><b>Error handling:</b></dt> |
| 65 |
* <dd>When the {@link #onError(Throwable)} is called, the {@code PublishSubject} enters into a terminal state |
| 66 |
* and emits the same {@code Throwable} instance to the last set of {@code Observer}s. During this emission, |
| 67 |
* if one or more {@code Observer}s dispose their respective {@code Disposable}s, the |
| 68 |
* {@code Throwable} is delivered to the global error handler via |
| 69 |
* {@link io.reactivex.rxjava3.plugins.RxJavaPlugins#onError(Throwable)} (multiple times if multiple {@code Observer}s |
| 70 |
* cancel at once). |
| 71 |
* If there were no {@code Observer}s subscribed to this {@code PublishSubject} when the {@code onError()} |
| 72 |
* was called, the global error handler is not invoked. |
| 73 |
* </dd> |
| 74 |
* </dl> |
| 75 |
* <p> |
| 76 |
* Example usage: |
| 77 |
* <pre> {@code |
| 78 |
|
| 79 |
PublishSubject<Object> subject = PublishSubject.create(); |
| 80 |
// observer1 will receive all onNext and onComplete events |
| 81 |
subject.subscribe(observer1); |
| 82 |
subject.onNext("one"); |
| 83 |
subject.onNext("two"); |
| 84 |
// observer2 will only receive "three" and onComplete |
| 85 |
subject.subscribe(observer2); |
| 86 |
subject.onNext("three"); |
| 87 |
subject.onComplete(); |
| 88 |
|
| 89 |
// late Observers only receive the terminal event |
| 90 |
subject.test().assertEmpty(); |
| 91 |
} </pre> |
| 92 |
* |
| 93 |
* @param <T> |
| 94 |
* the type of items observed and emitted by the Subject |
| 95 |
*/ |
| 96 |
public final class PublishSubject<T> extends Subject<T> { |
| 97 |
/** The terminated indicator for the subscribers array. */ |
| 98 |
@SuppressWarnings("rawtypes") |
| 99 |
static final PublishDisposable[] TERMINATED = new PublishDisposable[0]; |
| 100 |
/** An empty subscribers array to avoid allocating it all the time. */ |
| 101 |
@SuppressWarnings("rawtypes") |
| 102 |
static final PublishDisposable[] EMPTY = new PublishDisposable[0]; |
| 103 |
|
| 104 |
/** The array of currently subscribed subscribers. */ |
| 105 |
final AtomicReference<PublishDisposable<T>[]> subscribers; |
| 106 |
|
| 107 |
/** The error, write before terminating and read after checking subscribers. */ |
| 108 |
Throwable error; |
| 109 |
|
| 110 |
/** |
| 111 |
* Constructs a PublishSubject. |
| 112 |
* @param <T> the value type |
| 113 |
* @return the new PublishSubject |
| 114 |
*/ |
| 115 |
@CheckReturnValue |
| 116 |
@NonNull |
| 117 |
public static <T> PublishSubject<T> create() { |
| 118 |
return new PublishSubject<>(); |
| 119 |
} |
| 120 |
|
| 121 |
/** |
| 122 |
* Constructs a PublishSubject. |
| 123 |
* @since 2.0 |
| 124 |
*/ |
| 125 |
@SuppressWarnings("unchecked") |
| 126 |
PublishSubject() { |
| 127 |
subscribers = new AtomicReference<>(EMPTY); |
| 128 |
} |
| 129 |
|
| 130 |
@Override |
| 131 |
protected void subscribeActual(Observer<? super T> t) { |
| 132 |
PublishDisposable<T> ps = new PublishDisposable<>(t, this); |
| 133 |
t.onSubscribe(ps); |
| 134 |
if (add(ps)) { |
| 135 |
// if cancellation happened while a successful add, the remove() didn't work |
| 136 |
// so we need to do it again |
| 137 |
if (ps.isDisposed()) { |
| 138 |
remove(ps); |
| 139 |
} |
| 140 |
} else { |
| 141 |
Throwable ex = error; |
| 142 |
if (ex != null) { |
| 143 |
t.onError(ex); |
| 144 |
} else { |
| 145 |
t.onComplete(); |
| 146 |
} |
| 147 |
} |
| 148 |
} |
| 149 |
|
| 150 |
/** |
| 151 |
* Tries to add the given subscriber to the subscribers array atomically |
| 152 |
* or returns false if the subject has terminated. |
| 153 |
* @param ps the subscriber to add |
| 154 |
* @return true if successful, false if the subject has terminated |
| 155 |
*/ |
| 156 |
boolean add(PublishDisposable<T> ps) { |
| 157 |
for (;;) { |
| 158 |
PublishDisposable<T>[] a = subscribers.get(); |
| 159 |
if (a == TERMINATED) { |
| 160 |
return false; |
| 161 |
} |
| 162 |
|
| 163 |
int n = a.length; |
| 164 |
@SuppressWarnings("unchecked") |
| 165 |
PublishDisposable<T>[] b = new PublishDisposable[n + 1]; |
| 166 |
System.arraycopy(a, 0, b, 0, n); |
| 167 |
b[n] = ps; |
| 168 |
|
| 169 |
if (subscribers.compareAndSet(a, b)) { |
| 170 |
return true; |
| 171 |
} |
| 172 |
} |
| 173 |
} |
| 174 |
|
| 175 |
/** |
| 176 |
* Atomically removes the given subscriber if it is subscribed to the subject. |
| 177 |
* @param ps the subject to remove |
| 178 |
*/ |
| 179 |
@SuppressWarnings("unchecked") |
| 180 |
void remove(PublishDisposable<T> ps) { |
| 181 |
for (;;) { |
| 182 |
PublishDisposable<T>[] a = subscribers.get(); |
| 183 |
if (a == TERMINATED || a == EMPTY) { |
| 184 |
return; |
| 185 |
} |
| 186 |
|
| 187 |
int n = a.length; |
| 188 |
int j = -1; |
| 189 |
for (int i = 0; i < n; i++) { |
| 190 |
if (a[i] == ps) { |
| 191 |
j = i; |
| 192 |
break; |
| 193 |
} |
| 194 |
} |
| 195 |
|
| 196 |
if (j < 0) { |
| 197 |
return; |
| 198 |
} |
| 199 |
|
| 200 |
PublishDisposable<T>[] b; |
| 201 |
|
| 202 |
if (n == 1) { |
| 203 |
b = EMPTY; |
| 204 |
} else { |
| 205 |
b = new PublishDisposable[n - 1]; |
| 206 |
System.arraycopy(a, 0, b, 0, j); |
| 207 |
System.arraycopy(a, j + 1, b, j, n - j - 1); |
| 208 |
} |
| 209 |
if (subscribers.compareAndSet(a, b)) { |
| 210 |
return; |
| 211 |
} |
| 212 |
} |
| 213 |
} |
| 214 |
|
| 215 |
@Override |
| 216 |
public void onSubscribe(Disposable d) { |
| 217 |
if (subscribers.get() == TERMINATED) { |
| 218 |
d.dispose(); |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
@Override |
| 223 |
public void onNext(T t) { |
| 224 |
ExceptionHelper.nullCheck(t, "onNext called with a null value."); |
| 225 |
for (PublishDisposable<T> pd : subscribers.get()) { |
| 226 |
pd.onNext(t); |
| 227 |
} |
| 228 |
} |
| 229 |
|
| 230 |
@SuppressWarnings("unchecked") |
| 231 |
@Override |
| 232 |
public void onError(Throwable t) { |
| 233 |
ExceptionHelper.nullCheck(t, "onError called with a null Throwable."); |
| 234 |
if (subscribers.get() == TERMINATED) { |
| 235 |
RxJavaPlugins.onError(t); |
| 236 |
return; |
| 237 |
} |
| 238 |
error = t; |
| 239 |
|
| 240 |
for (PublishDisposable<T> pd : subscribers.getAndSet(TERMINATED)) { |
| 241 |
pd.onError(t); |
| 242 |
} |
| 243 |
} |
| 244 |
|
| 245 |
@SuppressWarnings("unchecked") |
| 246 |
@Override |
| 247 |
public void onComplete() { |
| 248 |
if (subscribers.get() == TERMINATED) { |
| 249 |
return; |
| 250 |
} |
| 251 |
for (PublishDisposable<T> pd : subscribers.getAndSet(TERMINATED)) { |
| 252 |
pd.onComplete(); |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
@Override |
| 257 |
@CheckReturnValue |
| 258 |
public boolean hasObservers() { |
| 259 |
return subscribers.get().length != 0; |
| 260 |
} |
| 261 |
|
| 262 |
@Override |
| 263 |
@Nullable |
| 264 |
@CheckReturnValue |
| 265 |
public Throwable getThrowable() { |
| 266 |
if (subscribers.get() == TERMINATED) { |
| 267 |
return error; |
| 268 |
} |
| 269 |
return null; |
| 270 |
} |
| 271 |
|
| 272 |
@Override |
| 273 |
@CheckReturnValue |
| 274 |
public boolean hasThrowable() { |
| 275 |
return subscribers.get() == TERMINATED && error != null; |
| 276 |
} |
| 277 |
|
| 278 |
@Override |
| 279 |
@CheckReturnValue |
| 280 |
public boolean hasComplete() { |
| 281 |
return subscribers.get() == TERMINATED && error == null; |
| 282 |
} |
| 283 |
|
| 284 |
/** |
| 285 |
* Wraps the actual subscriber, tracks its requests and makes cancellation |
| 286 |
* to remove itself from the current subscribers array. |
| 287 |
* |
| 288 |
* @param <T> the value type |
| 289 |
*/ |
| 290 |
static final class PublishDisposable<T> extends AtomicBoolean implements Disposable { |
| 291 |
|
| 292 |
private static final long serialVersionUID = 3562861878281475070L; |
| 293 |
/** The actual subscriber. */ |
| 294 |
final Observer<? super T> downstream; |
| 295 |
/** The subject state. */ |
| 296 |
final PublishSubject<T> parent; |
| 297 |
|
| 298 |
/** |
| 299 |
* Constructs a PublishSubscriber, wraps the actual subscriber and the state. |
| 300 |
* @param actual the actual subscriber |
| 301 |
* @param parent the parent PublishProcessor |
| 302 |
*/ |
| 303 |
PublishDisposable(Observer<? super T> actual, PublishSubject<T> parent) { |
| 304 |
this.downstream = actual; |
| 305 |
this.parent = parent; |
| 306 |
} |
| 307 |
|
| 308 |
public void onNext(T t) { |
| 309 |
if (!get()) { |
| 310 |
downstream.onNext(t); |
| 311 |
} |
| 312 |
} |
| 313 |
|
| 314 |
public void onError(Throwable t) { |
| 315 |
if (get()) { |
| 316 |
RxJavaPlugins.onError(t); |
| 317 |
} else { |
| 318 |
downstream.onError(t); |
| 319 |
} |
| 320 |
} |
| 321 |
|
| 322 |
public void onComplete() { |
| 323 |
if (!get()) { |
| 324 |
downstream.onComplete(); |
| 325 |
} |
| 326 |
} |
| 327 |
|
| 328 |
@Override |
| 329 |
public void dispose() { |
| 330 |
if (compareAndSet(false, true)) { |
| 331 |
parent.remove(this); |
| 332 |
} |
| 333 |
} |
| 334 |
|
| 335 |
@Override |
| 336 |
public boolean isDisposed() { |
| 337 |
return get(); |
| 338 |
} |
| 339 |
} |
| 340 |
} |