Debian Codegraph @

src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowablePublishMulticast.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.internal.operators.flowable;
15
16 import java.util.Objects;
17 import java.util.concurrent.atomic.*;
18
19 import org.reactivestreams.*;
20
21 import io.reactivex.rxjava3.core.*;
22 import io.reactivex.rxjava3.exceptions.*;
23 import io.reactivex.rxjava3.functions.Function;
24 import io.reactivex.rxjava3.internal.subscriptions.*;
25 import io.reactivex.rxjava3.internal.util.*;
26 import io.reactivex.rxjava3.operators.QueueSubscription;
27 import io.reactivex.rxjava3.operators.SimpleQueue;
28 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
29
30 /**
31 * Multicasts a Flowable over a selector function.
32 *
33 * @param <T> the input value type
34 * @param <R> the output value type
35 */
36 public final class FlowablePublishMulticast<T, R> extends AbstractFlowableWithUpstream<T, R> {
37
38 final Function<? super Flowable<T>, ? extends Publisher<? extends R>> selector;
39
40 final int prefetch;
41
42 final boolean delayError;
43
44 public FlowablePublishMulticast(Flowable<T> source,
45 Function<? super Flowable<T>, ? extends Publisher<? extends R>> selector, int prefetch,
46 boolean delayError) {
47 super(source);
48 this.selector = selector;
49 this.prefetch = prefetch;
50 this.delayError = delayError;
51 }
52
53 @Override
54 protected void subscribeActual(Subscriber<? super R> s) {
55 MulticastProcessor<T> mp = new MulticastProcessor<>(prefetch, delayError);
56
57 Publisher<? extends R> other;
58
59 try {
60 other = Objects.requireNonNull(selector.apply(mp), "selector returned a null Publisher");
61 } catch (Throwable ex) {
62 Exceptions.throwIfFatal(ex);
63 EmptySubscription.error(ex, s);
64 return;
65 }
66
67 OutputCanceller<R> out = new OutputCanceller<>(s, mp);
68
69 other.subscribe(out);
70
71 source.subscribe(mp);
72 }
73
74 static final class OutputCanceller<R> implements FlowableSubscriber<R>, Subscription {
75 final Subscriber<? super R> downstream;
76
77 final MulticastProcessor<?> processor;
78
79 Subscription upstream;
80
81 OutputCanceller(Subscriber<? super R> actual, MulticastProcessor<?> processor) {
82 this.downstream = actual;
83 this.processor = processor;
84 }
85
86 @Override
87 public void onSubscribe(Subscription s) {
88 if (SubscriptionHelper.validate(this.upstream, s)) {
89 this.upstream = s;
90
91 downstream.onSubscribe(this);
92 }
93 }
94
95 @Override
96 public void onNext(R t) {
97 downstream.onNext(t);
98 }
99
100 @Override
101 public void onError(Throwable t) {
102 downstream.onError(t);
103 processor.dispose();
104 }
105
106 @Override
107 public void onComplete() {
108 downstream.onComplete();
109 processor.dispose();
110 }
111
112 @Override
113 public void request(long n) {
114 upstream.request(n);
115 }
116
117 @Override
118 public void cancel() {
119 upstream.cancel();
120 processor.dispose();
121 }
122 }
123
124 static final class MulticastProcessor<T> extends Flowable<T> implements FlowableSubscriber<T> {
125
126 @SuppressWarnings("rawtypes")
127 static final MulticastSubscription[] EMPTY = new MulticastSubscription[0];
128
129 @SuppressWarnings("rawtypes")
130 static final MulticastSubscription[] TERMINATED = new MulticastSubscription[0];
131
132 final AtomicInteger wip;
133
134 final AtomicReference<MulticastSubscription<T>[]> subscribers;
135
136 final int prefetch;
137
138 final int limit;
139
140 final boolean delayError;
141
142 final AtomicReference<Subscription> upstream;
143
144 volatile SimpleQueue<T> queue;
145
146 int sourceMode;
147
148 volatile boolean done;
149 Throwable error;
150
151 int consumed;
152
153 @SuppressWarnings("unchecked")
154 MulticastProcessor(int prefetch, boolean delayError) {
155 this.prefetch = prefetch;
156 this.limit = prefetch - (prefetch >> 2); // request after 75% consumption
157 this.delayError = delayError;
158 this.wip = new AtomicInteger();
159 this.upstream = new AtomicReference<>();
160 this.subscribers = new AtomicReference<>(EMPTY);
161 }
162
163 @Override
164 public void onSubscribe(Subscription s) {
165 if (SubscriptionHelper.setOnce(this.upstream, s)) {
166 if (s instanceof QueueSubscription) {
167 @SuppressWarnings("unchecked")
168 QueueSubscription<T> qs = (QueueSubscription<T>) s;
169
170 int m = qs.requestFusion(QueueSubscription.ANY);
171 if (m == QueueSubscription.SYNC) {
172 sourceMode = m;
173 queue = qs;
174 done = true;
175 drain();
176 return;
177 }
178 if (m == QueueSubscription.ASYNC) {
179 sourceMode = m;
180 queue = qs;
181 QueueDrainHelper.request(s, prefetch);
182 return;
183 }
184 }
185
186 queue = QueueDrainHelper.createQueue(prefetch);
187
188 QueueDrainHelper.request(s, prefetch);
189 }
190 }
191
192 void dispose() {
193 if (!done) {
194 SubscriptionHelper.cancel(upstream);
195 if (wip.getAndIncrement() == 0) {
196 SimpleQueue<T> q = queue;
197 if (q != null) {
198 q.clear();
199 }
200 }
201 }
202 }
203
204 boolean isDisposed() {
205 return upstream.get() == SubscriptionHelper.CANCELLED;
206 }
207
208 @Override
209 public void onNext(T t) {
210 if (done) {
211 return;
212 }
213 if (sourceMode == QueueSubscription.NONE && !queue.offer(t)) {
214 upstream.get().cancel();
215 onError(new MissingBackpressureException());
216 return;
217 }
218 drain();
219 }
220
221 @Override
222 public void onError(Throwable t) {
223 if (done) {
224 RxJavaPlugins.onError(t);
225 return;
226 }
227 error = t;
228 done = true;
229 drain();
230 }
231
232 @Override
233 public void onComplete() {
234 if (!done) {
235 done = true;
236 drain();
237 }
238 }
239
240 boolean add(MulticastSubscription<T> s) {
241 for (;;) {
242 MulticastSubscription<T>[] current = subscribers.get();
243 if (current == TERMINATED) {
244 return false;
245 }
246 int n = current.length;
247 @SuppressWarnings("unchecked")
248 MulticastSubscription<T>[] next = new MulticastSubscription[n + 1];
249 System.arraycopy(current, 0, next, 0, n);
250 next[n] = s;
251 if (subscribers.compareAndSet(current, next)) {
252 return true;
253 }
254 }
255 }
256
257 @SuppressWarnings("unchecked")
258 void remove(MulticastSubscription<T> s) {
259 for (;;) {
260 MulticastSubscription<T>[] current = subscribers.get();
261 int n = current.length;
262 if (n == 0) {
263 return;
264 }
265 int j = -1;
266
267 for (int i = 0; i < n; i++) {
268 if (current[i] == s) {
269 j = i;
270 break;
271 }
272 }
273
274 if (j < 0) {
275 return;
276 }
277 MulticastSubscription<T>[] next;
278 if (n == 1) {
279 next = EMPTY;
280 } else {
281 next = new MulticastSubscription[n - 1];
282 System.arraycopy(current, 0, next, 0, j);
283 System.arraycopy(current, j + 1, next, j, n - j - 1);
284 }
285 if (subscribers.compareAndSet(current, next)) {
286 return;
287 }
288 }
289 }
290
291 @Override
292 protected void subscribeActual(Subscriber<? super T> s) {
293 MulticastSubscription<T> ms = new MulticastSubscription<>(s, this);
294 s.onSubscribe(ms);
295 if (add(ms)) {
296 if (ms.isCancelled()) {
297 remove(ms);
298 return;
299 }
300 drain();
301 } else {
302 Throwable ex = error;
303 if (ex != null) {
304 s.onError(ex);
305 } else {
306 s.onComplete();
307 }
308 }
309 }
310
311 void drain() {
312 if (wip.getAndIncrement() != 0) {
313 return;
314 }
315
316 int missed = 1;
317
318 SimpleQueue<T> q = queue;
319
320 int upstreamConsumed = consumed;
321 int localLimit = limit;
322 boolean canRequest = sourceMode != QueueSubscription.SYNC;
323 AtomicReference<MulticastSubscription<T>[]> subs = subscribers;
324
325 MulticastSubscription<T>[] array = subs.get();
326
327 outer:
328 for (;;) {
329
330 int n = array.length;
331
332 if (q != null && n != 0) {
333 long r = Long.MAX_VALUE;
334
335 for (MulticastSubscription<T> ms : array) {
336 long u = ms.get() - ms.emitted;
337 if (u != Long.MIN_VALUE) {
338 if (r > u) {
339 r = u;
340 }
341 } else {
342 n--;
343 }
344 }
345
346 if (n == 0) {
347 r = 0;
348 }
349
350 while (r != 0) {
351 if (isDisposed()) {
352 q.clear();
353 return;
354 }
355
356 boolean d = done;
357
358 if (d && !delayError) {
359 Throwable ex = error;
360 if (ex != null) {
361 errorAll(ex);
362 return;
363 }
364 }
365
366 T v;
367
368 try {
369 v = q.poll();
370 } catch (Throwable ex) {
371 Exceptions.throwIfFatal(ex);
372 SubscriptionHelper.cancel(upstream);
373 errorAll(ex);
374 return;
375 }
376
377 boolean empty = v == null;
378
379 if (d && empty) {
380 Throwable ex = error;
381 if (ex != null) {
382 errorAll(ex);
383 } else {
384 completeAll();
385 }
386 return;
387 }
388
389 if (empty) {
390 break;
391 }
392
393 boolean subscribersChange = false;
394
395 for (MulticastSubscription<T> ms : array) {
396 long msr = ms.get();
397 if (msr != Long.MIN_VALUE) {
398 if (msr != Long.MAX_VALUE) {
399 ms.emitted++;
400 }
401 ms.downstream.onNext(v);
402 } else {
403 subscribersChange = true;
404 }
405 }
406
407 r--;
408
409 if (canRequest && ++upstreamConsumed == localLimit) {
410 upstreamConsumed = 0;
411 upstream.get().request(localLimit);
412 }
413
414 MulticastSubscription<T>[] freshArray = subs.get();
415 if (subscribersChange || freshArray != array) {
416 array = freshArray;
417 continue outer;
418 }
419 }
420
421 if (r == 0) {
422 if (isDisposed()) {
423 q.clear();
424 return;
425 }
426
427 boolean d = done;
428
429 if (d && !delayError) {
430 Throwable ex = error;
431 if (ex != null) {
432 errorAll(ex);
433 return;
434 }
435 }
436
437 if (d && q.isEmpty()) {
438 Throwable ex = error;
439 if (ex != null) {
440 errorAll(ex);
441 } else {
442 completeAll();
443 }
444 return;
445 }
446 }
447 }
448
449 consumed = upstreamConsumed;
450 missed = wip.addAndGet(-missed);
451 if (missed == 0) {
452 break;
453 }
454 if (q == null) {
455 q = queue;
456 }
457 array = subs.get();
458 }
459 }
460
461 @SuppressWarnings("unchecked")
462 void errorAll(Throwable ex) {
463 for (MulticastSubscription<T> ms : subscribers.getAndSet(TERMINATED)) {
464 if (ms.get() != Long.MIN_VALUE) {
465 ms.downstream.onError(ex);
466 }
467 }
468 }
469
470 @SuppressWarnings("unchecked")
471 void completeAll() {
472 for (MulticastSubscription<T> ms : subscribers.getAndSet(TERMINATED)) {
473 if (ms.get() != Long.MIN_VALUE) {
474 ms.downstream.onComplete();
475 }
476 }
477 }
478 }
479
480 static final class MulticastSubscription<T>
481 extends AtomicLong
482 implements Subscription {
483
484 private static final long serialVersionUID = 8664815189257569791L;
485
486 final Subscriber<? super T> downstream;
487
488 final MulticastProcessor<T> parent;
489
490 long emitted;
491
492 MulticastSubscription(Subscriber<? super T> actual, MulticastProcessor<T> parent) {
493 this.downstream = actual;
494 this.parent = parent;
495 }
496
497 @Override
498 public void request(long n) {
499 if (SubscriptionHelper.validate(n)) {
500 BackpressureHelper.addCancel(this, n);
501 parent.drain();
502 }
503 }
504
505 @Override
506 public void cancel() {
507 if (getAndSet(Long.MIN_VALUE) != Long.MIN_VALUE) {
508 parent.remove(this);
509 parent.drain(); // unblock the others
510 }
511 }
512
513 public boolean isCancelled() {
514 return get() == Long.MIN_VALUE;
515 }
516 }
517 }