| 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.processors; |
| 15 |
|
| 16 |
import java.util.concurrent.atomic.*; |
| 17 |
|
| 18 |
import org.reactivestreams.*; |
| 19 |
|
| 20 |
import io.reactivex.rxjava3.annotations.*; |
| 21 |
import io.reactivex.rxjava3.exceptions.MissingBackpressureException; |
| 22 |
import io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper; |
| 23 |
import io.reactivex.rxjava3.internal.util.*; |
| 24 |
import io.reactivex.rxjava3.plugins.RxJavaPlugins; |
| 25 |
|
| 26 |
/** |
| 27 |
* Processor that multicasts all subsequently observed items to its current {@link Subscriber}s. |
| 28 |
* |
| 29 |
* <p> |
| 30 |
* <img width="640" height="278" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/PublishProcessor.png" alt=""> |
| 31 |
* <p> |
| 32 |
* This processor does not have a public constructor by design; a new empty instance of this |
| 33 |
* {@code PublishProcessor} can be created via the {@link #create()} method. |
| 34 |
* <p> |
| 35 |
* Since a {@code PublishProcessor} is a Reactive Streams {@code Processor} type, |
| 36 |
* {@code null}s are not allowed (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.13">Rule 2.13</a>) as |
| 37 |
* parameters to {@link #onNext(Object)} and {@link #onError(Throwable)}. Such calls will result in a |
| 38 |
* {@link NullPointerException} being thrown and the processor's state is not changed. |
| 39 |
* <p> |
| 40 |
* {@code PublishProcessor} is a {@link io.reactivex.rxjava3.core.Flowable} as well as a {@link FlowableProcessor}, |
| 41 |
* however, it does not coordinate backpressure between different subscribers and between an |
| 42 |
* upstream source and a subscriber. If an upstream item is received via {@link #onNext(Object)}, if |
| 43 |
* a subscriber is not ready to receive an item, that subscriber is terminated via a {@link MissingBackpressureException}. |
| 44 |
* To avoid this case, use {@link #offer(Object)} and retry sometime later if it returned false. |
| 45 |
* The {@code PublishProcessor}'s {@link Subscriber}-side consumes items in an unbounded manner. |
| 46 |
* <p> |
| 47 |
* For a multicasting processor type that also coordinates between the downstream {@code Subscriber}s and the upstream |
| 48 |
* source as well, consider using {@link MulticastProcessor}. |
| 49 |
* <p> |
| 50 |
* When this {@code PublishProcessor} is terminated via {@link #onError(Throwable)} or {@link #onComplete()}, |
| 51 |
* late {@link Subscriber}s only receive the respective terminal event. |
| 52 |
* <p> |
| 53 |
* Unlike a {@link BehaviorProcessor}, a {@code PublishProcessor} doesn't retain/cache items, therefore, a new |
| 54 |
* {@code Subscriber} won't receive any past items. |
| 55 |
* <p> |
| 56 |
* Even though {@code PublishProcessor} implements the {@link Subscriber} interface, calling |
| 57 |
* {@code onSubscribe} is not required (<a href="https://github.com/reactive-streams/reactive-streams-jvm#2.12">Rule 2.12</a>) |
| 58 |
* if the processor is used as a standalone source. However, calling {@code onSubscribe} |
| 59 |
* after the {@code PublishProcessor} reached its terminal state will result in the |
| 60 |
* given {@link Subscription} being canceled immediately. |
| 61 |
* <p> |
| 62 |
* Calling {@link #onNext(Object)}, {@link #offer(Object)}, {@link #onError(Throwable)} and {@link #onComplete()} |
| 63 |
* is required to be serialized (called from the same thread or called non-overlappingly from different threads |
| 64 |
* through external means of serialization). The {@link #toSerialized()} method available to all {@link FlowableProcessor}s |
| 65 |
* provides such serialization and also protects against reentrance (i.e., when a downstream {@code Subscriber} |
| 66 |
* consuming this processor also wants to call {@link #onNext(Object)} on this processor recursively). |
| 67 |
* Note that serializing over {@link #offer(Object)} is not supported through {@code toSerialized()} because it is a method |
| 68 |
* available on the {@code PublishProcessor} and {@code BehaviorProcessor} classes only. |
| 69 |
* <p> |
| 70 |
* This {@code PublishProcessor} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()}, |
| 71 |
* {@link #getThrowable()} and {@link #hasSubscribers()}. |
| 72 |
* <dl> |
| 73 |
* <dt><b>Backpressure:</b></dt> |
| 74 |
* <dd>The processor does not coordinate backpressure for its subscribers and implements a weaker {@code onSubscribe} which |
| 75 |
* calls requests {@link Long#MAX_VALUE} from the incoming Subscriptions. This makes it possible to subscribe the {@code PublishProcessor} |
| 76 |
* to multiple sources (note on serialization though) unlike the standard {@code Subscriber} contract. Child subscribers, however, are not overflown but receive an |
| 77 |
* {@link IllegalStateException} in case their requested amount is zero.</dd> |
| 78 |
* <dt><b>Scheduler:</b></dt> |
| 79 |
* <dd>{@code PublishProcessor} does not operate by default on a particular {@link io.reactivex.rxjava3.core.Scheduler} and |
| 80 |
* the {@code Subscriber}s get notified on the thread the respective {@code onXXX} methods were invoked.</dd> |
| 81 |
* <dt><b>Error handling:</b></dt> |
| 82 |
* <dd>When the {@link #onError(Throwable)} is called, the {@code PublishProcessor} enters into a terminal state |
| 83 |
* and emits the same {@code Throwable} instance to the last set of {@code Subscriber}s. During this emission, |
| 84 |
* if one or more {@code Subscriber}s cancel their respective {@code Subscription}s, the |
| 85 |
* {@code Throwable} is delivered to the global error handler via |
| 86 |
* {@link io.reactivex.rxjava3.plugins.RxJavaPlugins#onError(Throwable)} (multiple times if multiple {@code Subscriber}s |
| 87 |
* cancel at once). |
| 88 |
* If there were no {@code Subscriber}s subscribed to this {@code PublishProcessor} when the {@code onError()} |
| 89 |
* was called, the global error handler is not invoked. |
| 90 |
* </dd> |
| 91 |
* </dl> |
| 92 |
* |
| 93 |
* Example usage: |
| 94 |
* <pre> {@code |
| 95 |
|
| 96 |
PublishProcessor<Object> processor = PublishProcessor.create(); |
| 97 |
// subscriber1 will receive all onNext and onComplete events |
| 98 |
processor.subscribe(subscriber1); |
| 99 |
processor.onNext("one"); |
| 100 |
processor.onNext("two"); |
| 101 |
// subscriber2 will only receive "three" and onComplete |
| 102 |
processor.subscribe(subscriber2); |
| 103 |
processor.onNext("three"); |
| 104 |
processor.onComplete(); |
| 105 |
|
| 106 |
} </pre> |
| 107 |
* @param <T> the value type multicasted to Subscribers. |
| 108 |
* @see MulticastProcessor |
| 109 |
*/ |
| 110 |
public final class PublishProcessor<@NonNull T> extends FlowableProcessor<T> { |
| 111 |
/** The terminated indicator for the subscribers array. */ |
| 112 |
@SuppressWarnings("rawtypes") |
| 113 |
static final PublishSubscription[] TERMINATED = new PublishSubscription[0]; |
| 114 |
/** An empty subscribers array to avoid allocating it all the time. */ |
| 115 |
@SuppressWarnings("rawtypes") |
| 116 |
static final PublishSubscription[] EMPTY = new PublishSubscription[0]; |
| 117 |
|
| 118 |
/** The array of currently subscribed subscribers. */ |
| 119 |
final AtomicReference<PublishSubscription<T>[]> subscribers; |
| 120 |
|
| 121 |
/** The error, write before terminating and read after checking subscribers. */ |
| 122 |
Throwable error; |
| 123 |
|
| 124 |
/** |
| 125 |
* Constructs a PublishProcessor. |
| 126 |
* @param <T> the value type |
| 127 |
* @return the new PublishProcessor |
| 128 |
*/ |
| 129 |
@CheckReturnValue |
| 130 |
@NonNull |
| 131 |
public static <T> PublishProcessor<T> create() { |
| 132 |
return new PublishProcessor<>(); |
| 133 |
} |
| 134 |
|
| 135 |
/** |
| 136 |
* Constructs a PublishProcessor. |
| 137 |
* @since 2.0 |
| 138 |
*/ |
| 139 |
@SuppressWarnings("unchecked") |
| 140 |
PublishProcessor() { |
| 141 |
subscribers = new AtomicReference<>(EMPTY); |
| 142 |
} |
| 143 |
|
| 144 |
@Override |
| 145 |
protected void subscribeActual(@NonNull Subscriber<? super T> t) { |
| 146 |
PublishSubscription<T> ps = new PublishSubscription<>(t, this); |
| 147 |
t.onSubscribe(ps); |
| 148 |
if (add(ps)) { |
| 149 |
// if cancellation happened while a successful add, the remove() didn't work |
| 150 |
// so we need to do it again |
| 151 |
if (ps.isCancelled()) { |
| 152 |
remove(ps); |
| 153 |
} |
| 154 |
} else { |
| 155 |
Throwable ex = error; |
| 156 |
if (ex != null) { |
| 157 |
t.onError(ex); |
| 158 |
} else { |
| 159 |
t.onComplete(); |
| 160 |
} |
| 161 |
} |
| 162 |
} |
| 163 |
|
| 164 |
/** |
| 165 |
* Tries to add the given subscriber to the subscribers array atomically |
| 166 |
* or returns false if this processor has terminated. |
| 167 |
* @param ps the subscriber to add |
| 168 |
* @return true if successful, false if this processor has terminated |
| 169 |
*/ |
| 170 |
boolean add(PublishSubscription<T> ps) { |
| 171 |
for (;;) { |
| 172 |
PublishSubscription<T>[] a = subscribers.get(); |
| 173 |
if (a == TERMINATED) { |
| 174 |
return false; |
| 175 |
} |
| 176 |
|
| 177 |
int n = a.length; |
| 178 |
@SuppressWarnings("unchecked") |
| 179 |
PublishSubscription<T>[] b = new PublishSubscription[n + 1]; |
| 180 |
System.arraycopy(a, 0, b, 0, n); |
| 181 |
b[n] = ps; |
| 182 |
|
| 183 |
if (subscribers.compareAndSet(a, b)) { |
| 184 |
return true; |
| 185 |
} |
| 186 |
} |
| 187 |
} |
| 188 |
|
| 189 |
/** |
| 190 |
* Atomically removes the given subscriber if it is subscribed to this processor. |
| 191 |
* @param ps the subscription wrapping a subscriber to remove |
| 192 |
*/ |
| 193 |
@SuppressWarnings("unchecked") |
| 194 |
void remove(PublishSubscription<T> ps) { |
| 195 |
for (;;) { |
| 196 |
PublishSubscription<T>[] a = subscribers.get(); |
| 197 |
if (a == TERMINATED || a == EMPTY) { |
| 198 |
return; |
| 199 |
} |
| 200 |
|
| 201 |
int n = a.length; |
| 202 |
int j = -1; |
| 203 |
for (int i = 0; i < n; i++) { |
| 204 |
if (a[i] == ps) { |
| 205 |
j = i; |
| 206 |
break; |
| 207 |
} |
| 208 |
} |
| 209 |
|
| 210 |
if (j < 0) { |
| 211 |
return; |
| 212 |
} |
| 213 |
|
| 214 |
PublishSubscription<T>[] b; |
| 215 |
|
| 216 |
if (n == 1) { |
| 217 |
b = EMPTY; |
| 218 |
} else { |
| 219 |
b = new PublishSubscription[n - 1]; |
| 220 |
System.arraycopy(a, 0, b, 0, j); |
| 221 |
System.arraycopy(a, j + 1, b, j, n - j - 1); |
| 222 |
} |
| 223 |
if (subscribers.compareAndSet(a, b)) { |
| 224 |
return; |
| 225 |
} |
| 226 |
} |
| 227 |
} |
| 228 |
|
| 229 |
@Override |
| 230 |
public void onSubscribe(@NonNull Subscription s) { |
| 231 |
if (subscribers.get() == TERMINATED) { |
| 232 |
s.cancel(); |
| 233 |
return; |
| 234 |
} |
| 235 |
// PublishProcessor doesn't bother with request coordination. |
| 236 |
s.request(Long.MAX_VALUE); |
| 237 |
} |
| 238 |
|
| 239 |
@Override |
| 240 |
public void onNext(@NonNull T t) { |
| 241 |
ExceptionHelper.nullCheck(t, "onNext called with a null value."); |
| 242 |
for (PublishSubscription<T> s : subscribers.get()) { |
| 243 |
s.onNext(t); |
| 244 |
} |
| 245 |
} |
| 246 |
|
| 247 |
@SuppressWarnings("unchecked") |
| 248 |
@Override |
| 249 |
public void onError(@NonNull Throwable t) { |
| 250 |
ExceptionHelper.nullCheck(t, "onError called with a null Throwable."); |
| 251 |
if (subscribers.get() == TERMINATED) { |
| 252 |
RxJavaPlugins.onError(t); |
| 253 |
return; |
| 254 |
} |
| 255 |
error = t; |
| 256 |
|
| 257 |
for (PublishSubscription<T> s : subscribers.getAndSet(TERMINATED)) { |
| 258 |
s.onError(t); |
| 259 |
} |
| 260 |
} |
| 261 |
|
| 262 |
@SuppressWarnings("unchecked") |
| 263 |
@Override |
| 264 |
public void onComplete() { |
| 265 |
if (subscribers.get() == TERMINATED) { |
| 266 |
return; |
| 267 |
} |
| 268 |
for (PublishSubscription<T> s : subscribers.getAndSet(TERMINATED)) { |
| 269 |
s.onComplete(); |
| 270 |
} |
| 271 |
} |
| 272 |
|
| 273 |
/** |
| 274 |
* Tries to emit the item to all currently subscribed {@link Subscriber}s if all of them |
| 275 |
* has requested some value, returns {@code false} otherwise. |
| 276 |
* <p> |
| 277 |
* This method should be called in a sequential manner just like the {@code onXXX} methods |
| 278 |
* of this {@code PublishProcessor}. |
| 279 |
* <p>History: 2.0.8 - experimental |
| 280 |
* @param t the item to emit, not {@code null} |
| 281 |
* @return {@code true} if the item was emitted to all {@code Subscriber}s |
| 282 |
* @throws NullPointerException if {@code t} is {@code null} |
| 283 |
* @since 2.2 |
| 284 |
*/ |
| 285 |
@CheckReturnValue |
| 286 |
public boolean offer(@NonNull T t) { |
| 287 |
ExceptionHelper.nullCheck(t, "offer called with a null value."); |
| 288 |
|
| 289 |
PublishSubscription<T>[] array = subscribers.get(); |
| 290 |
|
| 291 |
for (PublishSubscription<T> s : array) { |
| 292 |
if (s.isFull()) { |
| 293 |
return false; |
| 294 |
} |
| 295 |
} |
| 296 |
|
| 297 |
for (PublishSubscription<T> s : array) { |
| 298 |
s.onNext(t); |
| 299 |
} |
| 300 |
return true; |
| 301 |
} |
| 302 |
|
| 303 |
@Override |
| 304 |
@CheckReturnValue |
| 305 |
public boolean hasSubscribers() { |
| 306 |
return subscribers.get().length != 0; |
| 307 |
} |
| 308 |
|
| 309 |
@Override |
| 310 |
@Nullable |
| 311 |
@CheckReturnValue |
| 312 |
public Throwable getThrowable() { |
| 313 |
if (subscribers.get() == TERMINATED) { |
| 314 |
return error; |
| 315 |
} |
| 316 |
return null; |
| 317 |
} |
| 318 |
|
| 319 |
@Override |
| 320 |
@CheckReturnValue |
| 321 |
public boolean hasThrowable() { |
| 322 |
return subscribers.get() == TERMINATED && error != null; |
| 323 |
} |
| 324 |
|
| 325 |
@Override |
| 326 |
@CheckReturnValue |
| 327 |
public boolean hasComplete() { |
| 328 |
return subscribers.get() == TERMINATED && error == null; |
| 329 |
} |
| 330 |
|
| 331 |
/** |
| 332 |
* Wraps the actual subscriber, tracks its requests and makes cancellation |
| 333 |
* to remove itself from the current subscribers array. |
| 334 |
* |
| 335 |
* @param <T> the value type |
| 336 |
*/ |
| 337 |
static final class PublishSubscription<@NonNull T> extends AtomicLong implements Subscription { |
| 338 |
|
| 339 |
private static final long serialVersionUID = 3562861878281475070L; |
| 340 |
/** The actual subscriber. */ |
| 341 |
final Subscriber<? super T> downstream; |
| 342 |
/** The parent processor servicing this subscriber. */ |
| 343 |
final PublishProcessor<T> parent; |
| 344 |
|
| 345 |
/** |
| 346 |
* Constructs a PublishSubscriber, wraps the actual subscriber and the state. |
| 347 |
* @param actual the actual subscriber |
| 348 |
* @param parent the parent PublishProcessor |
| 349 |
*/ |
| 350 |
PublishSubscription(Subscriber<? super T> actual, PublishProcessor<T> parent) { |
| 351 |
this.downstream = actual; |
| 352 |
this.parent = parent; |
| 353 |
} |
| 354 |
|
| 355 |
public void onNext(T t) { |
| 356 |
long r = get(); |
| 357 |
if (r == Long.MIN_VALUE) { |
| 358 |
return; |
| 359 |
} |
| 360 |
if (r != 0L) { |
| 361 |
downstream.onNext(t); |
| 362 |
BackpressureHelper.producedCancel(this, 1); |
| 363 |
} else { |
| 364 |
cancel(); |
| 365 |
downstream.onError(new MissingBackpressureException("Could not emit value due to lack of requests")); |
| 366 |
} |
| 367 |
} |
| 368 |
|
| 369 |
public void onError(Throwable t) { |
| 370 |
if (get() != Long.MIN_VALUE) { |
| 371 |
downstream.onError(t); |
| 372 |
} else { |
| 373 |
RxJavaPlugins.onError(t); |
| 374 |
} |
| 375 |
} |
| 376 |
|
| 377 |
public void onComplete() { |
| 378 |
if (get() != Long.MIN_VALUE) { |
| 379 |
downstream.onComplete(); |
| 380 |
} |
| 381 |
} |
| 382 |
|
| 383 |
@Override |
| 384 |
public void request(long n) { |
| 385 |
if (SubscriptionHelper.validate(n)) { |
| 386 |
BackpressureHelper.addCancel(this, n); |
| 387 |
} |
| 388 |
} |
| 389 |
|
| 390 |
@Override |
| 391 |
public void cancel() { |
| 392 |
if (getAndSet(Long.MIN_VALUE) != Long.MIN_VALUE) { |
| 393 |
parent.remove(this); |
| 394 |
} |
| 395 |
} |
| 396 |
|
| 397 |
public boolean isCancelled() { |
| 398 |
return get() == Long.MIN_VALUE; |
| 399 |
} |
| 400 |
|
| 401 |
boolean isFull() { |
| 402 |
return get() == 0L; |
| 403 |
} |
| 404 |
} |
| 405 |
} |