Debian Codegraph @

src/test/java/io/reactivex/rxjava3/testsupport/TestHelper.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.testsupport;
15
16 import static org.junit.Assert.*;
17 import static org.mockito.ArgumentMatchers.any;
18 import static org.mockito.Mockito.mock;
19
20 import java.io.File;
21 import java.lang.management.*;
22 import java.lang.reflect.*;
23 import java.net.URL;
24 import java.util.*;
25 import java.util.concurrent.*;
26 import java.util.concurrent.atomic.AtomicInteger;
27
28 import org.mockito.Mockito;
29 import org.mockito.invocation.InvocationOnMock;
30 import org.mockito.stubbing.Answer;
31 import org.reactivestreams.*;
32
33 import io.reactivex.rxjava3.annotations.*;
34 import io.reactivex.rxjava3.core.*;
35 import io.reactivex.rxjava3.core.Observable;
36 import io.reactivex.rxjava3.core.Observer;
37 import io.reactivex.rxjava3.disposables.*;
38 import io.reactivex.rxjava3.exceptions.*;
39 import io.reactivex.rxjava3.functions.*;
40 import io.reactivex.rxjava3.internal.operators.completable.CompletableToFlowable;
41 import io.reactivex.rxjava3.internal.operators.maybe.MaybeToFlowable;
42 import io.reactivex.rxjava3.internal.operators.single.SingleToFlowable;
43 import io.reactivex.rxjava3.internal.subscriptions.*;
44 import io.reactivex.rxjava3.internal.util.ExceptionHelper;
45 import io.reactivex.rxjava3.observers.BaseTestConsumer;
46 import io.reactivex.rxjava3.operators.ConditionalSubscriber;
47 import io.reactivex.rxjava3.operators.QueueDisposable;
48 import io.reactivex.rxjava3.operators.QueueFuseable;
49 import io.reactivex.rxjava3.operators.QueueSubscription;
50 import io.reactivex.rxjava3.operators.SimpleQueue;
51 import io.reactivex.rxjava3.parallel.ParallelFlowable;
52 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
53 import io.reactivex.rxjava3.processors.PublishProcessor;
54 import io.reactivex.rxjava3.schedulers.Schedulers;
55 import io.reactivex.rxjava3.subjects.Subject;
56 import io.reactivex.rxjava3.subscribers.TestSubscriber;
57
58 /**
59 * Common methods for helping with tests.
60 */
61 public enum TestHelper {
62 ;
63
64 /**
65 * Number of times to loop a {@link #race(Runnable, Runnable)} invocation
66 * by default.
67 */
68 public static final int RACE_DEFAULT_LOOPS = 2500;
69
70 /**
71 * Number of times to loop a {@link #race(Runnable, Runnable)} invocation
72 * in tests with race conditions requiring more runs to check.
73 */
74 public static final int RACE_LONG_LOOPS = 10000;
75
76 /**
77 * Mocks a subscriber and prepares it to request {@link Long#MAX_VALUE}.
78 * @param <T> the value type
79 * @return the mocked subscriber
80 */
81 @SuppressWarnings("unchecked")
82 public static <T> FlowableSubscriber<T> mockSubscriber() {
83 FlowableSubscriber<T> w = mock(FlowableSubscriber.class);
84
85 Mockito.doAnswer(new Answer<Object>() {
86 @Override
87 public Object answer(InvocationOnMock a) throws Throwable {
88 Subscription s = a.getArgument(0);
89 s.request(Long.MAX_VALUE);
90 return null;
91 }
92 }).when(w).onSubscribe((Subscription)any());
93
94 return w;
95 }
96
97 /**
98 * Mocks an Observer with the proper receiver type.
99 * @param <T> the value type
100 * @return the mocked observer
101 */
102 @SuppressWarnings("unchecked")
103 public static <T> Observer<T> mockObserver() {
104 return mock(Observer.class);
105 }
106
107 /**
108 * Mocks an MaybeObserver with the proper receiver type.
109 * @param <T> the value type
110 * @return the mocked observer
111 */
112 @SuppressWarnings("unchecked")
113 public static <T> MaybeObserver<T> mockMaybeObserver() {
114 return mock(MaybeObserver.class);
115 }
116
117 /**
118 * Mocks an SingleObserver with the proper receiver type.
119 * @param <T> the value type
120 * @return the mocked observer
121 */
122 @SuppressWarnings("unchecked")
123 public static <T> SingleObserver<T> mockSingleObserver() {
124 return mock(SingleObserver.class);
125 }
126
127 /**
128 * Mocks an CompletableObserver.
129 * @return the mocked observer
130 */
131 public static CompletableObserver mockCompletableObserver() {
132 return mock(CompletableObserver.class);
133 }
134
135 /**
136 * Validates that the given class, when forcefully instantiated throws
137 * an IllegalArgumentException("No instances!") exception.
138 * @param clazz the class to test, not null
139 */
140 public static void checkUtilityClass(Class<?> clazz) {
141 try {
142 Constructor<?> c = clazz.getDeclaredConstructor();
143
144 c.setAccessible(true);
145
146 try {
147 c.newInstance();
148 fail("Should have thrown InvocationTargetException(IllegalStateException)");
149 } catch (InvocationTargetException ex) {
150 assertEquals("No instances!", ex.getCause().getMessage());
151 }
152 } catch (Exception ex) {
153 AssertionError ae = new AssertionError(ex.toString());
154 ae.initCause(ex);
155 throw ae;
156 }
157 }
158
159 public static List<Throwable> trackPluginErrors() {
160 final List<Throwable> list = Collections.synchronizedList(new ArrayList<>());
161
162 RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
163 @Override
164 public void accept(Throwable t) {
165 list.add(t);
166 }
167 });
168
169 return list;
170 }
171
172 public static void assertError(List<Throwable> list, int index, Class<? extends Throwable> clazz) {
173 Throwable ex = list.get(index);
174 if (!clazz.isInstance(ex)) {
175 AssertionError err = new AssertionError(clazz + " expected but got " + list.get(index));
176 err.initCause(list.get(index));
177 throw err;
178 }
179 }
180
181 public static void assertUndeliverable(List<Throwable> list, int index, Class<? extends Throwable> clazz) {
182 Throwable ex = list.get(index);
183 if (!(ex instanceof UndeliverableException)) {
184 AssertionError err = new AssertionError("Outer exception UndeliverableException expected but got " + list.get(index));
185 err.initCause(list.get(index));
186 throw err;
187 }
188 ex = ex.getCause();
189 if (!clazz.isInstance(ex)) {
190 AssertionError err = new AssertionError("Inner exception " + clazz + " expected but got " + list.get(index));
191 err.initCause(list.get(index));
192 throw err;
193 }
194 }
195
196 public static void assertError(List<Throwable> list, int index, Class<? extends Throwable> clazz, String message) {
197 Throwable ex = list.get(index);
198 if (!clazz.isInstance(ex)) {
199 AssertionError err = new AssertionError("Type " + clazz + " expected but got " + ex);
200 err.initCause(ex);
201 throw err;
202 }
203 if (!Objects.equals(message, ex.getMessage())) {
204 AssertionError err = new AssertionError("Message " + message + " expected but got " + ex.getMessage());
205 err.initCause(ex);
206 throw err;
207 }
208 }
209
210 public static void assertUndeliverable(List<Throwable> list, int index, Class<? extends Throwable> clazz, String message) {
211 Throwable ex = list.get(index);
212 if (!(ex instanceof UndeliverableException)) {
213 AssertionError err = new AssertionError("Outer exception UndeliverableException expected but got " + list.get(index));
214 err.initCause(list.get(index));
215 throw err;
216 }
217 ex = ex.getCause();
218 if (!clazz.isInstance(ex)) {
219 AssertionError err = new AssertionError("Inner exception " + clazz + " expected but got " + list.get(index));
220 err.initCause(list.get(index));
221 throw err;
222 }
223 if (!Objects.equals(message, ex.getMessage())) {
224 AssertionError err = new AssertionError("Message " + message + " expected but got " + ex.getMessage());
225 err.initCause(ex);
226 throw err;
227 }
228 }
229
230 public static void assertError(TestObserverEx<?> to, int index, Class<? extends Throwable> clazz) {
231 Throwable ex = to.errors().get(0);
232 try {
233 if (ex instanceof CompositeException) {
234 CompositeException ce = (CompositeException) ex;
235 List<Throwable> cel = ce.getExceptions();
236 assertTrue(cel.get(index).toString(), clazz.isInstance(cel.get(index)));
237 } else {
238 fail(ex.toString() + ": not a CompositeException");
239 }
240 } catch (AssertionError e) {
241 ex.printStackTrace();
242 throw e;
243 }
244 }
245
246 public static void assertError(TestSubscriberEx<?> ts, int index, Class<? extends Throwable> clazz) {
247 Throwable ex = ts.errors().get(0);
248 if (ex instanceof CompositeException) {
249 CompositeException ce = (CompositeException) ex;
250 List<Throwable> cel = ce.getExceptions();
251 assertTrue(cel.get(index).toString(), clazz.isInstance(cel.get(index)));
252 } else {
253 fail(ex.toString() + ": not a CompositeException");
254 }
255 }
256
257 public static void assertError(TestObserverEx<?> to, int index, Class<? extends Throwable> clazz, String message) {
258 Throwable ex = to.errors().get(0);
259 if (ex instanceof CompositeException) {
260 CompositeException ce = (CompositeException) ex;
261 List<Throwable> cel = ce.getExceptions();
262 assertTrue(cel.get(index).toString(), clazz.isInstance(cel.get(index)));
263 assertEquals(message, cel.get(index).getMessage());
264 } else {
265 fail(ex.toString() + ": not a CompositeException");
266 }
267 }
268
269 public static void assertError(TestSubscriberEx<?> ts, int index, Class<? extends Throwable> clazz, String message) {
270 Throwable ex = ts.errors().get(0);
271 if (ex instanceof CompositeException) {
272 CompositeException ce = (CompositeException) ex;
273 List<Throwable> cel = ce.getExceptions();
274 assertTrue(cel.get(index).toString(), clazz.isInstance(cel.get(index)));
275 assertEquals(message, cel.get(index).getMessage());
276 } else {
277 fail(ex.toString() + ": not a CompositeException");
278 }
279 }
280
281 /**
282 * Verify that a specific enum type has no enum constants.
283 * @param <E> the enum type
284 * @param e the enum class instance
285 */
286 public static <E extends Enum<E>> void assertEmptyEnum(Class<E> e) {
287 assertEquals(0, e.getEnumConstants().length);
288
289 try {
290 try {
291 Method m0 = e.getDeclaredMethod("values");
292
293 Object[] a = (Object[])m0.invoke(null);
294 assertEquals(0, a.length);
295
296 Method m = e.getDeclaredMethod("valueOf", String.class);
297
298 m.invoke("INSTANCE");
299 fail("Should have thrown!");
300 } catch (InvocationTargetException ex) {
301 fail(ex.toString());
302 } catch (IllegalAccessException ex) {
303 fail(ex.toString());
304 } catch (IllegalArgumentException ex) {
305 // we expected this
306 }
307 } catch (NoSuchMethodException ex) {
308 fail(ex.toString());
309 }
310 }
311
312 /**
313 * Assert that by consuming the Publisher with a bad request amount, it is
314 * reported to the plugin error handler promptly.
315 * @param source the source to consume
316 */
317 public static void assertBadRequestReported(Publisher<?> source) {
318 List<Throwable> list = trackPluginErrors();
319 try {
320 final CountDownLatch cdl = new CountDownLatch(1);
321
322 source.subscribe(new FlowableSubscriber<Object>() {
323
324 @Override
325 public void onSubscribe(Subscription s) {
326 try {
327 s.request(-99);
328 s.cancel();
329 s.cancel();
330 } finally {
331 cdl.countDown();
332 }
333 }
334
335 @Override
336 public void onNext(Object t) {
337
338 }
339
340 @Override
341 public void onError(Throwable t) {
342
343 }
344
345 @Override
346 public void onComplete() {
347
348 }
349
350 });
351
352 try {
353 assertTrue(cdl.await(5, TimeUnit.SECONDS));
354 } catch (InterruptedException ex) {
355 throw new AssertionError(ex.getMessage());
356 }
357
358 assertTrue(list.toString(), list.get(0) instanceof IllegalArgumentException);
359 assertEquals("n > 0 required but it was -99", list.get(0).getMessage());
360 } finally {
361 RxJavaPlugins.setErrorHandler(null);
362 }
363 }
364
365 /**
366 * Assert that by consuming the Publisher with a bad request amount, it is
367 * reported to the plugin error handler promptly.
368 * @param source the source to consume
369 */
370 public static void assertBadRequestReported(ParallelFlowable<?> source) {
371 List<Throwable> list = trackPluginErrors();
372 try {
373 final CountDownLatch cdl = new CountDownLatch(1);
374
375 FlowableSubscriber<Object> bad = new FlowableSubscriber<Object>() {
376
377 @Override
378 public void onSubscribe(Subscription s) {
379 try {
380 s.request(-99);
381 s.cancel();
382 s.cancel();
383 } finally {
384 cdl.countDown();
385 }
386 }
387
388 @Override
389 public void onNext(Object t) {
390
391 }
392
393 @Override
394 public void onError(Throwable t) {
395
396 }
397
398 @Override
399 public void onComplete() {
400
401 }
402
403 };
404
405 @SuppressWarnings("unchecked")
406 FlowableSubscriber<Object>[] subs = new FlowableSubscriber[source.parallelism()];
407 subs[0] = bad;
408 for (int i = 1; i < subs.length; i++) {
409 subs[i] = NoOpConsumer.INSTANCE;
410 }
411 source.subscribe(subs);
412
413 try {
414 assertTrue(cdl.await(5, TimeUnit.SECONDS));
415 } catch (InterruptedException ex) {
416 throw new AssertionError(ex.getMessage());
417 }
418
419 assertTrue(list.toString(), list.get(0) instanceof IllegalArgumentException);
420 assertEquals("n > 0 required but it was -99", list.get(0).getMessage());
421 } finally {
422 RxJavaPlugins.setErrorHandler(null);
423 }
424 }
425
426 /**
427 * Synchronizes the execution of two runnables (as much as possible)
428 * to test race conditions.
429 * <p>The method blocks until both have run to completion.
430 * @param r1 the first runnable
431 * @param r2 the second runnable
432 * @see #RACE_DEFAULT_LOOPS
433 * @see #RACE_LONG_LOOPS
434 */
435 public static void race(final Runnable r1, final Runnable r2) {
436 race(r1, r2, Schedulers.single());
437 }
438 /**
439 * Synchronizes the execution of two runnables (as much as possible)
440 * to test race conditions.
441 * <p>The method blocks until both have run to completion.
442 * @param r1 the first runnable
443 * @param r2 the second runnable
444 * @param s the scheduler to use
445 * @see #RACE_DEFAULT_LOOPS
446 * @see #RACE_LONG_LOOPS
447 */
448 public static void race(final Runnable r1, final Runnable r2, Scheduler s) {
449 final AtomicInteger count = new AtomicInteger(2);
450 final CountDownLatch cdl = new CountDownLatch(2);
451
452 final Throwable[] errors = { null, null };
453
454 s.scheduleDirect(new Runnable() {
455 @Override
456 public void run() {
457 if (count.decrementAndGet() != 0) {
458 while (count.get() != 0) { }
459 }
460
461 try {
462 try {
463 r1.run();
464 } catch (Throwable ex) {
465 errors[0] = ex;
466 }
467 } finally {
468 cdl.countDown();
469 }
470 }
471 });
472
473 if (count.decrementAndGet() != 0) {
474 while (count.get() != 0) { }
475 }
476
477 try {
478 try {
479 r2.run();
480 } catch (Throwable ex) {
481 errors[1] = ex;
482 }
483 } finally {
484 cdl.countDown();
485 }
486
487 try {
488 if (!cdl.await(5, TimeUnit.SECONDS)) {
489 throw new AssertionError("The wait timed out!");
490 }
491 } catch (InterruptedException ex) {
492 throw new RuntimeException(ex);
493 }
494 if (errors[0] != null && errors[1] == null) {
495 throw ExceptionHelper.wrapOrThrow(errors[0]);
496 }
497
498 if (errors[0] == null && errors[1] != null) {
499 throw ExceptionHelper.wrapOrThrow(errors[1]);
500 }
501
502 if (errors[0] != null && errors[1] != null) {
503 throw new CompositeException(errors);
504 }
505 }
506
507 /**
508 * Cast the given Throwable to CompositeException and returns its inner
509 * Throwable list.
510 * @param ex the target Throwable
511 * @return the list of Throwables
512 */
513 public static List<Throwable> compositeList(Throwable ex) {
514 if (ex instanceof UndeliverableException) {
515 ex = ex.getCause();
516 }
517 return ((CompositeException)ex).getExceptions();
518 }
519
520 /**
521 * Assert that the offer methods throw UnsupportedOperationExcetpion.
522 * @param q the queue implementation
523 */
524 public static void assertNoOffer(SimpleQueue<?> q) {
525 try {
526 q.offer(null);
527 fail("Should have thrown!");
528 } catch (UnsupportedOperationException ex) {
529 // expected
530 }
531 try {
532 q.offer(null, null);
533 fail("Should have thrown!");
534 } catch (UnsupportedOperationException ex) {
535 // expected
536 }
537 }
538
539 @SuppressWarnings("unchecked")
540 public static <E extends Enum<E>> void checkEnum(Class<E> enumClass) {
541 try {
542 Method m = enumClass.getMethod("values");
543 m.setAccessible(true);
544 Method e = enumClass.getMethod("valueOf", String.class);
545 m.setAccessible(true);
546
547 for (Enum<E> o : (Enum<E>[])m.invoke(null)) {
548 assertSame(o, e.invoke(null, o.name()));
549 }
550
551 } catch (Throwable ex) {
552 throw ExceptionHelper.wrapOrThrow(ex);
553 }
554 }
555
556 /**
557 * Calls onSubscribe twice and checks if it doesn't affect the first Subscription while
558 * reporting it to plugin error handler.
559 * @param subscriber the target
560 */
561 public static void doubleOnSubscribe(Subscriber<?> subscriber) {
562 List<Throwable> errors = trackPluginErrors();
563 try {
564 BooleanSubscription s1 = new BooleanSubscription();
565
566 subscriber.onSubscribe(s1);
567
568 BooleanSubscription s2 = new BooleanSubscription();
569
570 subscriber.onSubscribe(s2);
571
572 assertFalse(s1.isCancelled());
573
574 assertTrue(s2.isCancelled());
575
576 assertError(errors, 0, IllegalStateException.class, "Subscription already set!");
577 } finally {
578 RxJavaPlugins.reset();
579 }
580 }
581
582 /**
583 * Calls onSubscribe twice and checks if it doesn't affect the first Disposable while
584 * reporting it to plugin error handler.
585 * @param observer the target
586 */
587 public static void doubleOnSubscribe(Observer<?> observer) {
588 List<Throwable> errors = trackPluginErrors();
589 try {
590 Disposable d1 = Disposable.empty();
591
592 observer.onSubscribe(d1);
593
594 Disposable d2 = Disposable.empty();
595
596 observer.onSubscribe(d2);
597
598 assertFalse(d1.isDisposed());
599
600 assertTrue(d2.isDisposed());
601
602 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
603 } finally {
604 RxJavaPlugins.reset();
605 }
606 }
607
608 /**
609 * Calls onSubscribe twice and checks if it doesn't affect the first Disposable while
610 * reporting it to plugin error handler.
611 * @param observer the target
612 */
613 public static void doubleOnSubscribe(SingleObserver<?> observer) {
614 List<Throwable> errors = trackPluginErrors();
615 try {
616 Disposable d1 = Disposable.empty();
617
618 observer.onSubscribe(d1);
619
620 Disposable d2 = Disposable.empty();
621
622 observer.onSubscribe(d2);
623
624 assertFalse(d1.isDisposed());
625
626 assertTrue(d2.isDisposed());
627
628 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
629 } finally {
630 RxJavaPlugins.reset();
631 }
632 }
633
634 /**
635 * Calls onSubscribe twice and checks if it doesn't affect the first Disposable while
636 * reporting it to plugin error handler.
637 * @param observer the target
638 */
639 public static void doubleOnSubscribe(CompletableObserver observer) {
640 List<Throwable> errors = trackPluginErrors();
641 try {
642 Disposable d1 = Disposable.empty();
643
644 observer.onSubscribe(d1);
645
646 Disposable d2 = Disposable.empty();
647
648 observer.onSubscribe(d2);
649
650 assertFalse(d1.isDisposed());
651
652 assertTrue(d2.isDisposed());
653
654 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
655 } finally {
656 RxJavaPlugins.reset();
657 }
658 }
659
660 /**
661 * Calls onSubscribe twice and checks if it doesn't affect the first Disposable while
662 * reporting it to plugin error handler.
663 * @param observer the target
664 */
665 public static void doubleOnSubscribe(MaybeObserver<?> observer) {
666 List<Throwable> errors = trackPluginErrors();
667 try {
668 Disposable d1 = Disposable.empty();
669
670 observer.onSubscribe(d1);
671
672 Disposable d2 = Disposable.empty();
673
674 observer.onSubscribe(d2);
675
676 assertFalse(d1.isDisposed());
677
678 assertTrue(d2.isDisposed());
679
680 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
681 } finally {
682 RxJavaPlugins.reset();
683 }
684 }
685
686 public static void checkDisposed(Disposable d) {
687 assertFalse("Disposed upfront?!", d.isDisposed());
688
689 d.dispose();
690
691 assertTrue("Not disposed?!", d.isDisposed());
692
693 d.dispose();
694
695 assertTrue("Not disposed again?!", d.isDisposed());
696 }
697
698 /**
699 * Checks if the upstream's Subscription sent through the onSubscribe reports
700 * isCancelled properly before and after calling dispose.
701 * @param <T> the input value type
702 * @param source the source to test
703 */
704 public static <T> void checkDisposed(Flowable<T> source) {
705 final TestSubscriber<Object> ts = new TestSubscriber<>(0L);
706 source.subscribe(new FlowableSubscriber<Object>() {
707 @Override
708 public void onSubscribe(Subscription s) {
709 ts.onSubscribe(new BooleanSubscription());
710
711 s.cancel();
712
713 s.cancel();
714 }
715
716 @Override
717 public void onNext(Object t) {
718 ts.onNext(t);
719 }
720
721 @Override
722 public void onError(Throwable t) {
723 ts.onError(t);
724 }
725
726 @Override
727 public void onComplete() {
728 ts.onComplete();
729 }
730 });
731 ts.assertEmpty();
732 }
733 /**
734 * Checks if the upstream's Disposable sent through the onSubscribe reports
735 * isDisposed properly before and after calling dispose.
736 * @param source the source to test
737 */
738 public static void checkDisposed(Maybe<?> source) {
739 final Boolean[] b = { null, null };
740 final CountDownLatch cdl = new CountDownLatch(1);
741 source.subscribe(new MaybeObserver<Object>() {
742
743 @Override
744 public void onSubscribe(Disposable d) {
745 try {
746 b[0] = d.isDisposed();
747
748 d.dispose();
749
750 b[1] = d.isDisposed();
751
752 d.dispose();
753 } finally {
754 cdl.countDown();
755 }
756 }
757
758 @Override
759 public void onSuccess(Object value) {
760 // ignored
761 }
762
763 @Override
764 public void onError(Throwable e) {
765 // ignored
766 }
767
768 @Override
769 public void onComplete() {
770 // ignored
771 }
772 });
773
774 try {
775 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
776 } catch (InterruptedException ex) {
777 throw ExceptionHelper.wrapOrThrow(ex);
778 }
779
780 assertEquals("Reports disposed upfront?", false, b[0]);
781 assertEquals("Didn't report disposed after?", true, b[1]);
782 }
783
784 /**
785 * Checks if the upstream's Disposable sent through the onSubscribe reports
786 * isDisposed properly before and after calling dispose.
787 * @param source the source to test
788 */
789 public static void checkDisposed(Observable<?> source) {
790 final Boolean[] b = { null, null };
791 final CountDownLatch cdl = new CountDownLatch(1);
792 source.subscribe(new Observer<Object>() {
793
794 @Override
795 public void onSubscribe(Disposable d) {
796 try {
797 b[0] = d.isDisposed();
798
799 d.dispose();
800
801 b[1] = d.isDisposed();
802
803 d.dispose();
804 } finally {
805 cdl.countDown();
806 }
807 }
808
809 @Override
810 public void onNext(Object value) {
811 // ignored
812 }
813
814 @Override
815 public void onError(Throwable e) {
816 // ignored
817 }
818
819 @Override
820 public void onComplete() {
821 // ignored
822 }
823 });
824
825 try {
826 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
827 } catch (InterruptedException ex) {
828 throw ExceptionHelper.wrapOrThrow(ex);
829 }
830
831 assertEquals("Reports disposed upfront?", false, b[0]);
832 assertEquals("Didn't report disposed after?", true, b[1]);
833 }
834
835 /**
836 * Checks if the upstream's Disposable sent through the onSubscribe reports
837 * isDisposed properly before and after calling dispose.
838 * @param source the source to test
839 */
840 public static void checkDisposed(Single<?> source) {
841 final Boolean[] b = { null, null };
842 final CountDownLatch cdl = new CountDownLatch(1);
843 source.subscribe(new SingleObserver<Object>() {
844
845 @Override
846 public void onSubscribe(Disposable d) {
847 try {
848 b[0] = d.isDisposed();
849
850 d.dispose();
851
852 b[1] = d.isDisposed();
853
854 d.dispose();
855 } finally {
856 cdl.countDown();
857 }
858 }
859
860 @Override
861 public void onSuccess(Object value) {
862 // ignored
863 }
864
865 @Override
866 public void onError(Throwable e) {
867 // ignored
868 }
869 });
870
871 try {
872 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
873 } catch (InterruptedException ex) {
874 throw ExceptionHelper.wrapOrThrow(ex);
875 }
876
877 assertEquals("Reports disposed upfront?", false, b[0]);
878 assertEquals("Didn't report disposed after?", true, b[1]);
879 }
880
881 /**
882 * Checks if the upstream's Disposable sent through the onSubscribe reports
883 * isDisposed properly before and after calling dispose.
884 * @param source the source to test
885 */
886 public static void checkDisposed(Completable source) {
887 final Boolean[] b = { null, null };
888 final CountDownLatch cdl = new CountDownLatch(1);
889 source.subscribe(new CompletableObserver() {
890
891 @Override
892 public void onSubscribe(Disposable d) {
893 try {
894 b[0] = d.isDisposed();
895
896 d.dispose();
897
898 b[1] = d.isDisposed();
899
900 d.dispose();
901 } finally {
902 cdl.countDown();
903 }
904 }
905
906 @Override
907 public void onError(Throwable e) {
908 // ignored
909 }
910
911 @Override
912 public void onComplete() {
913 // ignored
914 }
915 });
916
917 try {
918 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
919 } catch (InterruptedException ex) {
920 throw ExceptionHelper.wrapOrThrow(ex);
921 }
922
923 assertEquals("Reports disposed upfront?", false, b[0]);
924 assertEquals("Didn't report disposed after?", true, b[1]);
925 }
926
927 /**
928 * Consumer for all base reactive types.
929 */
930 enum NoOpConsumer implements FlowableSubscriber<Object>, Observer<Object>, MaybeObserver<Object>, SingleObserver<Object>, CompletableObserver {
931 INSTANCE;
932
933 @Override
934 public void onSubscribe(Disposable d) {
935 // deliberately no-op
936 }
937
938 @Override
939 public void onSuccess(Object value) {
940 // deliberately no-op
941 }
942
943 @Override
944 public void onError(Throwable e) {
945 // deliberately no-op
946 }
947
948 @Override
949 public void onComplete() {
950 // deliberately no-op
951 }
952
953 @Override
954 public void onSubscribe(Subscription s) {
955 // deliberately no-op
956 }
957
958 @Override
959 public void onNext(Object t) {
960 // deliberately no-op
961 }
962 }
963
964 /**
965 * Check if the given transformed reactive type reports multiple onSubscribe calls to
966 * RxJavaPlugins.
967 * @param <T> the input value type
968 * @param <R> the output value type
969 * @param transform the transform to drive an operator
970 */
971 public static <T, R> void checkDoubleOnSubscribeMaybe(Function<Maybe<T>, ? extends MaybeSource<R>> transform) {
972 List<Throwable> errors = trackPluginErrors();
973 try {
974 final Boolean[] b = { null, null };
975 final CountDownLatch cdl = new CountDownLatch(1);
976
977 Maybe<T> source = new Maybe<T>() {
978 @Override
979 protected void subscribeActual(MaybeObserver<? super T> observer) {
980 try {
981 Disposable d1 = Disposable.empty();
982
983 observer.onSubscribe(d1);
984
985 Disposable d2 = Disposable.empty();
986
987 observer.onSubscribe(d2);
988
989 b[0] = d1.isDisposed();
990 b[1] = d2.isDisposed();
991 } finally {
992 cdl.countDown();
993 }
994 }
995 };
996
997 MaybeSource<R> out = transform.apply(source);
998
999 out.subscribe(NoOpConsumer.INSTANCE);
1000
1001 try {
1002 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
1003 } catch (InterruptedException ex) {
1004 throw ExceptionHelper.wrapOrThrow(ex);
1005 }
1006
1007 assertEquals("First disposed?", false, b[0]);
1008 assertEquals("Second not disposed?", true, b[1]);
1009
1010 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
1011 } catch (Throwable ex) {
1012 throw ExceptionHelper.wrapOrThrow(ex);
1013 } finally {
1014 RxJavaPlugins.reset();
1015 }
1016 }
1017
1018 /**
1019 * Check if the given transformed reactive type reports multiple onSubscribe calls to
1020 * RxJavaPlugins.
1021 * @param <T> the input value type
1022 * @param <R> the output value type
1023 * @param transform the transform to drive an operator
1024 */
1025 public static <T, R> void checkDoubleOnSubscribeMaybeToSingle(Function<Maybe<T>, ? extends SingleSource<R>> transform) {
1026 List<Throwable> errors = trackPluginErrors();
1027 try {
1028 final Boolean[] b = { null, null };
1029 final CountDownLatch cdl = new CountDownLatch(1);
1030
1031 Maybe<T> source = new Maybe<T>() {
1032 @Override
1033 protected void subscribeActual(MaybeObserver<? super T> observer) {
1034 try {
1035 Disposable d1 = Disposable.empty();
1036
1037 observer.onSubscribe(d1);
1038
1039 Disposable d2 = Disposable.empty();
1040
1041 observer.onSubscribe(d2);
1042
1043 b[0] = d1.isDisposed();
1044 b[1] = d2.isDisposed();
1045 } finally {
1046 cdl.countDown();
1047 }
1048 }
1049 };
1050
1051 SingleSource<R> out = transform.apply(source);
1052
1053 out.subscribe(NoOpConsumer.INSTANCE);
1054
1055 try {
1056 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
1057 } catch (InterruptedException ex) {
1058 throw ExceptionHelper.wrapOrThrow(ex);
1059 }
1060
1061 assertEquals("First disposed?", false, b[0]);
1062 assertEquals("Second not disposed?", true, b[1]);
1063
1064 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
1065 } catch (Throwable ex) {
1066 throw ExceptionHelper.wrapOrThrow(ex);
1067 } finally {
1068 RxJavaPlugins.reset();
1069 }
1070 }
1071
1072 /**
1073 * Check if the given transformed reactive type reports multiple onSubscribe calls to
1074 * RxJavaPlugins.
1075 * @param <T> the input value type
1076 * @param <R> the output value type
1077 * @param transform the transform to drive an operator
1078 */
1079 public static <T, R> void checkDoubleOnSubscribeMaybeToObservable(Function<Maybe<T>, ? extends ObservableSource<R>> transform) {
1080 List<Throwable> errors = trackPluginErrors();
1081 try {
1082 final Boolean[] b = { null, null };
1083 final CountDownLatch cdl = new CountDownLatch(1);
1084
1085 Maybe<T> source = new Maybe<T>() {
1086 @Override
1087 protected void subscribeActual(MaybeObserver<? super T> observer) {
1088 try {
1089 Disposable d1 = Disposable.empty();
1090
1091 observer.onSubscribe(d1);
1092
1093 Disposable d2 = Disposable.empty();
1094
1095 observer.onSubscribe(d2);
1096
1097 b[0] = d1.isDisposed();
1098 b[1] = d2.isDisposed();
1099 } finally {
1100 cdl.countDown();
1101 }
1102 }
1103 };
1104
1105 ObservableSource<R> out = transform.apply(source);
1106
1107 out.subscribe(NoOpConsumer.INSTANCE);
1108
1109 try {
1110 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
1111 } catch (InterruptedException ex) {
1112 throw ExceptionHelper.wrapOrThrow(ex);
1113 }
1114
1115 assertEquals("First disposed?", false, b[0]);
1116 assertEquals("Second not disposed?", true, b[1]);
1117
1118 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
1119 } catch (Throwable ex) {
1120 throw ExceptionHelper.wrapOrThrow(ex);
1121 } finally {
1122 RxJavaPlugins.reset();
1123 }
1124 }
1125
1126 /**
1127 * Check if the given transformed reactive type reports multiple onSubscribe calls to
1128 * RxJavaPlugins.
1129 * @param <T> the input value type
1130 * @param <R> the output value type
1131 * @param transform the transform to drive an operator
1132 */
1133 public static <T, R> void checkDoubleOnSubscribeMaybeToFlowable(Function<Maybe<T>, ? extends Publisher<R>> transform) {
1134 List<Throwable> errors = trackPluginErrors();
1135 try {
1136 final Boolean[] b = { null, null };
1137 final CountDownLatch cdl = new CountDownLatch(1);
1138
1139 Maybe<T> source = new Maybe<T>() {
1140 @Override
1141 protected void subscribeActual(MaybeObserver<? super T> observer) {
1142 try {
1143 Disposable d1 = Disposable.empty();
1144
1145 observer.onSubscribe(d1);
1146
1147 Disposable d2 = Disposable.empty();
1148
1149 observer.onSubscribe(d2);
1150
1151 b[0] = d1.isDisposed();
1152 b[1] = d2.isDisposed();
1153 } finally {
1154 cdl.countDown();
1155 }
1156 }
1157 };
1158
1159 Publisher<R> out = transform.apply(source);
1160
1161 out.subscribe(NoOpConsumer.INSTANCE);
1162
1163 try {
1164 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
1165 } catch (InterruptedException ex) {
1166 throw ExceptionHelper.wrapOrThrow(ex);
1167 }
1168
1169 assertEquals("First disposed?", false, b[0]);
1170 assertEquals("Second not disposed?", true, b[1]);
1171
1172 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
1173 } catch (Throwable ex) {
1174 throw ExceptionHelper.wrapOrThrow(ex);
1175 } finally {
1176 RxJavaPlugins.reset();
1177 }
1178 }
1179
1180 /**
1181 * Check if the given transformed reactive type reports multiple onSubscribe calls to
1182 * RxJavaPlugins.
1183 * @param <T> the input value type
1184 * @param <R> the output value type
1185 * @param transform the transform to drive an operator
1186 */
1187 public static <T, R> void checkDoubleOnSubscribeSingleToMaybe(Function<Single<T>, ? extends MaybeSource<R>> transform) {
1188 List<Throwable> errors = trackPluginErrors();
1189 try {
1190 final Boolean[] b = { null, null };
1191 final CountDownLatch cdl = new CountDownLatch(1);
1192
1193 Single<T> source = new Single<T>() {
1194 @Override
1195 protected void subscribeActual(SingleObserver<? super T> observer) {
1196 try {
1197 Disposable d1 = Disposable.empty();
1198
1199 observer.onSubscribe(d1);
1200
1201 Disposable d2 = Disposable.empty();
1202
1203 observer.onSubscribe(d2);
1204
1205 b[0] = d1.isDisposed();
1206 b[1] = d2.isDisposed();
1207 } finally {
1208 cdl.countDown();
1209 }
1210 }
1211 };
1212
1213 MaybeSource<R> out = transform.apply(source);
1214
1215 out.subscribe(NoOpConsumer.INSTANCE);
1216
1217 try {
1218 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
1219 } catch (InterruptedException ex) {
1220 throw ExceptionHelper.wrapOrThrow(ex);
1221 }
1222
1223 assertEquals("First disposed?", false, b[0]);
1224 assertEquals("Second not disposed?", true, b[1]);
1225
1226 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
1227 } catch (Throwable ex) {
1228 throw ExceptionHelper.wrapOrThrow(ex);
1229 } finally {
1230 RxJavaPlugins.reset();
1231 }
1232 }
1233
1234 /**
1235 * Check if the given transformed reactive type reports multiple onSubscribe calls to
1236 * RxJavaPlugins.
1237 * @param <T> the input value type
1238 * @param <R> the output value type
1239 * @param transform the transform to drive an operator
1240 */
1241 public static <T, R> void checkDoubleOnSubscribeSingleToObservable(Function<Single<T>, ? extends ObservableSource<R>> transform) {
1242 List<Throwable> errors = trackPluginErrors();
1243 try {
1244 final Boolean[] b = { null, null };
1245 final CountDownLatch cdl = new CountDownLatch(1);
1246
1247 Single<T> source = new Single<T>() {
1248 @Override
1249 protected void subscribeActual(SingleObserver<? super T> observer) {
1250 try {
1251 Disposable d1 = Disposable.empty();
1252
1253 observer.onSubscribe(d1);
1254
1255 Disposable d2 = Disposable.empty();
1256
1257 observer.onSubscribe(d2);
1258
1259 b[0] = d1.isDisposed();
1260 b[1] = d2.isDisposed();
1261 } finally {
1262 cdl.countDown();
1263 }
1264 }
1265 };
1266
1267 ObservableSource<R> out = transform.apply(source);
1268
1269 out.subscribe(NoOpConsumer.INSTANCE);
1270
1271 try {
1272 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
1273 } catch (InterruptedException ex) {
1274 throw ExceptionHelper.wrapOrThrow(ex);
1275 }
1276
1277 assertEquals("First disposed?", false, b[0]);
1278 assertEquals("Second not disposed?", true, b[1]);
1279
1280 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
1281 } catch (Throwable ex) {
1282 throw ExceptionHelper.wrapOrThrow(ex);
1283 } finally {
1284 RxJavaPlugins.reset();
1285 }
1286 }
1287
1288 /**
1289 * Check if the given transformed reactive type reports multiple onSubscribe calls to
1290 * RxJavaPlugins.
1291 * @param <T> the input value type
1292 * @param <R> the output value type
1293 * @param transform the transform to drive an operator
1294 */
1295 public static <T, R> void checkDoubleOnSubscribeSingleToFlowable(Function<Single<T>, ? extends Publisher<R>> transform) {
1296 List<Throwable> errors = trackPluginErrors();
1297 try {
1298 final Boolean[] b = { null, null };
1299 final CountDownLatch cdl = new CountDownLatch(1);
1300
1301 Single<T> source = new Single<T>() {
1302 @Override
1303 protected void subscribeActual(SingleObserver<? super T> observer) {
1304 try {
1305 Disposable d1 = Disposable.empty();
1306
1307 observer.onSubscribe(d1);
1308
1309 Disposable d2 = Disposable.empty();
1310
1311 observer.onSubscribe(d2);
1312
1313 b[0] = d1.isDisposed();
1314 b[1] = d2.isDisposed();
1315 } finally {
1316 cdl.countDown();
1317 }
1318 }
1319 };
1320
1321 Publisher<R> out = transform.apply(source);
1322
1323 out.subscribe(NoOpConsumer.INSTANCE);
1324
1325 try {
1326 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
1327 } catch (InterruptedException ex) {
1328 throw ExceptionHelper.wrapOrThrow(ex);
1329 }
1330
1331 assertEquals("First disposed?", false, b[0]);
1332 assertEquals("Second not disposed?", true, b[1]);
1333
1334 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
1335 } catch (Throwable ex) {
1336 throw ExceptionHelper.wrapOrThrow(ex);
1337 } finally {
1338 RxJavaPlugins.reset();
1339 }
1340 }
1341
1342 /**
1343 * Check if the given transformed reactive type reports multiple onSubscribe calls to
1344 * RxJavaPlugins.
1345 * @param <T> the input value type
1346 * @param transform the transform to drive an operator
1347 */
1348 public static <T> void checkDoubleOnSubscribeMaybeToCompletable(Function<Maybe<T>, ? extends CompletableSource> transform) {
1349 List<Throwable> errors = trackPluginErrors();
1350 try {
1351 final Boolean[] b = { null, null };
1352 final CountDownLatch cdl = new CountDownLatch(1);
1353
1354 Maybe<T> source = new Maybe<T>() {
1355 @Override
1356 protected void subscribeActual(MaybeObserver<? super T> observer) {
1357 try {
1358 Disposable d1 = Disposable.empty();
1359
1360 observer.onSubscribe(d1);
1361
1362 Disposable d2 = Disposable.empty();
1363
1364 observer.onSubscribe(d2);
1365
1366 b[0] = d1.isDisposed();
1367 b[1] = d2.isDisposed();
1368 } finally {
1369 cdl.countDown();
1370 }
1371 }
1372 };
1373
1374 CompletableSource out = transform.apply(source);
1375
1376 out.subscribe(NoOpConsumer.INSTANCE);
1377
1378 try {
1379 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
1380 } catch (InterruptedException ex) {
1381 throw ExceptionHelper.wrapOrThrow(ex);
1382 }
1383
1384 assertEquals("First disposed?", false, b[0]);
1385 assertEquals("Second not disposed?", true, b[1]);
1386
1387 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
1388 } catch (Throwable ex) {
1389 throw ExceptionHelper.wrapOrThrow(ex);
1390 } finally {
1391 RxJavaPlugins.reset();
1392 }
1393 }
1394
1395 /**
1396 * Check if the given transformed reactive type reports multiple onSubscribe calls to
1397 * RxJavaPlugins.
1398 * @param <T> the input value type
1399 * @param <R> the output value type
1400 * @param transform the transform to drive an operator
1401 */
1402 public static <T, R> void checkDoubleOnSubscribeSingle(Function<Single<T>, ? extends SingleSource<R>> transform) {
1403 List<Throwable> errors = trackPluginErrors();
1404 try {
1405 final Boolean[] b = { null, null };
1406 final CountDownLatch cdl = new CountDownLatch(1);
1407
1408 Single<T> source = new Single<T>() {
1409 @Override
1410 protected void subscribeActual(SingleObserver<? super T> observer) {
1411 try {
1412 Disposable d1 = Disposable.empty();
1413
1414 observer.onSubscribe(d1);
1415
1416 Disposable d2 = Disposable.empty();
1417
1418 observer.onSubscribe(d2);
1419
1420 b[0] = d1.isDisposed();
1421 b[1] = d2.isDisposed();
1422 } finally {
1423 cdl.countDown();
1424 }
1425 }
1426 };
1427
1428 SingleSource<R> out = transform.apply(source);
1429
1430 out.subscribe(NoOpConsumer.INSTANCE);
1431
1432 try {
1433 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
1434 } catch (InterruptedException ex) {
1435 throw ExceptionHelper.wrapOrThrow(ex);
1436 }
1437
1438 assertEquals("First disposed?", false, b[0]);
1439 assertEquals("Second not disposed?", true, b[1]);
1440
1441 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
1442 } catch (Throwable ex) {
1443 throw ExceptionHelper.wrapOrThrow(ex);
1444 } finally {
1445 RxJavaPlugins.reset();
1446 }
1447 }
1448
1449 /**
1450 * Check if the given transformed reactive type reports multiple onSubscribe calls to
1451 * RxJavaPlugins.
1452 * @param <T> the input value type
1453 * @param <R> the output value type
1454 * @param transform the transform to drive an operator
1455 */
1456 public static <T, R> void checkDoubleOnSubscribeFlowable(Function<Flowable<T>, ? extends Publisher<R>> transform) {
1457 List<Throwable> errors = trackPluginErrors();
1458 try {
1459 final Boolean[] b = { null, null };
1460 final CountDownLatch cdl = new CountDownLatch(1);
1461
1462 Flowable<T> source = new Flowable<T>() {
1463 @Override
1464 protected void subscribeActual(Subscriber<? super T> subscriber) {
1465 try {
1466 BooleanSubscription bs1 = new BooleanSubscription();
1467
1468 subscriber.onSubscribe(bs1);
1469
1470 BooleanSubscription bs2 = new BooleanSubscription();
1471
1472 subscriber.onSubscribe(bs2);
1473
1474 b[0] = bs1.isCancelled();
1475 b[1] = bs2.isCancelled();
1476 } finally {
1477 cdl.countDown();
1478 }
1479 }
1480 };
1481
1482 Publisher<R> out = transform.apply(source);
1483
1484 out.subscribe(NoOpConsumer.INSTANCE);
1485
1486 try {
1487 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
1488 } catch (InterruptedException ex) {
1489 throw ExceptionHelper.wrapOrThrow(ex);
1490 }
1491
1492 assertEquals("First disposed?", false, b[0]);
1493 assertEquals("Second not disposed?", true, b[1]);
1494
1495 assertError(errors, 0, IllegalStateException.class, "Subscription already set!");
1496 } catch (Throwable ex) {
1497 throw ExceptionHelper.wrapOrThrow(ex);
1498 } finally {
1499 RxJavaPlugins.reset();
1500 }
1501 }
1502
1503 /**
1504 * Check if the given transformed reactive type reports multiple onSubscribe calls to
1505 * RxJavaPlugins.
1506 * @param <T> the input value type
1507 * @param transform the transform to drive an operator
1508 */
1509 @SuppressWarnings("unchecked")
1510 public static <T> void checkDoubleOnSubscribeParallel(Function<ParallelFlowable<T>, ? extends ParallelFlowable<?>> transform) {
1511 List<Throwable> errors = trackPluginErrors();
1512 try {
1513 final Boolean[] b = { null, null, null, null };
1514 final CountDownLatch cdl = new CountDownLatch(2);
1515
1516 ParallelFlowable<T> source = new ParallelFlowable<T>() {
1517 @Override
1518 public void subscribe(Subscriber<? super T>[] subscribers) {
1519 for (int i = 0; i < subscribers.length; i++) {
1520 try {
1521 BooleanSubscription bs1 = new BooleanSubscription();
1522
1523 subscribers[i].onSubscribe(bs1);
1524
1525 BooleanSubscription bs2 = new BooleanSubscription();
1526
1527 subscribers[i].onSubscribe(bs2);
1528
1529 b[i * 2 + 0] = bs1.isCancelled();
1530 b[i * 2 + 1] = bs2.isCancelled();
1531 } finally {
1532 cdl.countDown();
1533 }
1534 }
1535 }
1536
1537 @Override
1538 public int parallelism() {
1539 return 2;
1540 }
1541 };
1542
1543 ParallelFlowable<?> out = transform.apply(source);
1544
1545 out.subscribe(new Subscriber[] { NoOpConsumer.INSTANCE, NoOpConsumer.INSTANCE });
1546
1547 try {
1548 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
1549 } catch (InterruptedException ex) {
1550 throw ExceptionHelper.wrapOrThrow(ex);
1551 }
1552
1553 assertEquals("Rail 1 First disposed?", false, b[0]);
1554 assertEquals("Rail 1 Second not disposed?", true, b[1]);
1555
1556 assertEquals("Rail 2 First disposed?", false, b[2]);
1557 assertEquals("Rail 2 Second not disposed?", true, b[3]);
1558
1559 assertError(errors, 0, IllegalStateException.class, "Subscription already set!");
1560 assertError(errors, 1, IllegalStateException.class, "Subscription already set!");
1561 } catch (Throwable ex) {
1562 throw ExceptionHelper.wrapOrThrow(ex);
1563 } finally {
1564 RxJavaPlugins.reset();
1565 }
1566 }
1567 /**
1568 * Check if the given transformed reactive type reports multiple onSubscribe calls to
1569 * RxJavaPlugins.
1570 * @param <T> the input value type
1571 * @param transform the transform to drive an operator
1572 */
1573 public static <T> void checkDoubleOnSubscribeParallelToFlowable(Function<ParallelFlowable<T>, ? extends Flowable<?>> transform) {
1574 List<Throwable> errors = trackPluginErrors();
1575 try {
1576 final Boolean[] b = { null, null, null, null };
1577 final CountDownLatch cdl = new CountDownLatch(2);
1578
1579 ParallelFlowable<T> source = new ParallelFlowable<T>() {
1580 @Override
1581 public void subscribe(Subscriber<? super T>[] subscribers) {
1582 for (int i = 0; i < subscribers.length; i++) {
1583 try {
1584 BooleanSubscription bs1 = new BooleanSubscription();
1585
1586 subscribers[i].onSubscribe(bs1);
1587
1588 BooleanSubscription bs2 = new BooleanSubscription();
1589
1590 subscribers[i].onSubscribe(bs2);
1591
1592 b[i * 2 + 0] = bs1.isCancelled();
1593 b[i * 2 + 1] = bs2.isCancelled();
1594 } finally {
1595 cdl.countDown();
1596 }
1597 }
1598 }
1599
1600 @Override
1601 public int parallelism() {
1602 return 2;
1603 }
1604 };
1605
1606 Flowable<?> out = transform.apply(source);
1607
1608 out.subscribe(NoOpConsumer.INSTANCE);
1609
1610 try {
1611 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
1612 } catch (InterruptedException ex) {
1613 throw ExceptionHelper.wrapOrThrow(ex);
1614 }
1615
1616 assertEquals("Rail 1 First disposed?", false, b[0]);
1617 assertEquals("Rail 1 Second not disposed?", true, b[1]);
1618
1619 assertEquals("Rail 2 First disposed?", false, b[2]);
1620 assertEquals("Rail 2 Second not disposed?", true, b[3]);
1621
1622 assertError(errors, 0, IllegalStateException.class, "Subscription already set!");
1623 assertError(errors, 1, IllegalStateException.class, "Subscription already set!");
1624 } catch (Throwable ex) {
1625 throw ExceptionHelper.wrapOrThrow(ex);
1626 } finally {
1627 RxJavaPlugins.reset();
1628 }
1629 }
1630
1631 /**
1632 * Check if the given transformed reactive type reports multiple onSubscribe calls to
1633 * RxJavaPlugins.
1634 * @param <T> the input value type
1635 * @param <R> the output value type
1636 * @param transform the transform to drive an operator
1637 */
1638 public static <T, R> void checkDoubleOnSubscribeObservable(Function<Observable<T>, ? extends ObservableSource<R>> transform) {
1639 List<Throwable> errors = trackPluginErrors();
1640 try {
1641 final Boolean[] b = { null, null };
1642 final CountDownLatch cdl = new CountDownLatch(1);
1643
1644 Observable<T> source = new Observable<T>() {
1645 @Override
1646 protected void subscribeActual(Observer<? super T> observer) {
1647 try {
1648 Disposable d1 = Disposable.empty();
1649
1650 observer.onSubscribe(d1);
1651
1652 Disposable d2 = Disposable.empty();
1653
1654 observer.onSubscribe(d2);
1655
1656 b[0] = d1.isDisposed();
1657 b[1] = d2.isDisposed();
1658 } finally {
1659 cdl.countDown();
1660 }
1661 }
1662 };
1663
1664 ObservableSource<R> out = transform.apply(source);
1665
1666 out.subscribe(NoOpConsumer.INSTANCE);
1667
1668 try {
1669 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
1670 } catch (InterruptedException ex) {
1671 throw ExceptionHelper.wrapOrThrow(ex);
1672 }
1673
1674 assertEquals("First disposed?", false, b[0]);
1675 assertEquals("Second not disposed?", true, b[1]);
1676
1677 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
1678 } catch (Throwable ex) {
1679 throw ExceptionHelper.wrapOrThrow(ex);
1680 } finally {
1681 RxJavaPlugins.reset();
1682 }
1683 }
1684
1685 /**
1686 * Check if the given transformed reactive type reports multiple onSubscribe calls to
1687 * RxJavaPlugins.
1688 * @param <T> the input value type
1689 * @param <R> the output value type
1690 * @param transform the transform to drive an operator
1691 */
1692 public static <T, R> void checkDoubleOnSubscribeObservableToSingle(Function<Observable<T>, ? extends SingleSource<R>> transform) {
1693 List<Throwable> errors = trackPluginErrors();
1694 try {
1695 final Boolean[] b = { null, null };
1696 final CountDownLatch cdl = new CountDownLatch(1);
1697
1698 Observable<T> source = new Observable<T>() {
1699 @Override
1700 protected void subscribeActual(Observer<? super T> observer) {
1701 try {
1702 Disposable d1 = Disposable.empty();
1703
1704 observer.onSubscribe(d1);
1705
1706 Disposable d2 = Disposable.empty();
1707
1708 observer.onSubscribe(d2);
1709
1710 b[0] = d1.isDisposed();
1711 b[1] = d2.isDisposed();
1712 } finally {
1713 cdl.countDown();
1714 }
1715 }
1716 };
1717
1718 SingleSource<R> out = transform.apply(source);
1719
1720 out.subscribe(NoOpConsumer.INSTANCE);
1721
1722 try {
1723 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
1724 } catch (InterruptedException ex) {
1725 throw ExceptionHelper.wrapOrThrow(ex);
1726 }
1727
1728 assertEquals("First disposed?", false, b[0]);
1729 assertEquals("Second not disposed?", true, b[1]);
1730
1731 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
1732 } catch (Throwable ex) {
1733 throw ExceptionHelper.wrapOrThrow(ex);
1734 } finally {
1735 RxJavaPlugins.reset();
1736 }
1737 }
1738
1739 /**
1740 * Check if the given transformed reactive type reports multiple onSubscribe calls to
1741 * RxJavaPlugins.
1742 * @param <T> the input value type
1743 * @param <R> the output value type
1744 * @param transform the transform to drive an operator
1745 */
1746 public static <T, R> void checkDoubleOnSubscribeObservableToMaybe(Function<Observable<T>, ? extends MaybeSource<R>> transform) {
1747 List<Throwable> errors = trackPluginErrors();
1748 try {
1749 final Boolean[] b = { null, null };
1750 final CountDownLatch cdl = new CountDownLatch(1);
1751
1752 Observable<T> source = new Observable<T>() {
1753 @Override
1754 protected void subscribeActual(Observer<? super T> observer) {
1755 try {
1756 Disposable d1 = Disposable.empty();
1757
1758 observer.onSubscribe(d1);
1759
1760 Disposable d2 = Disposable.empty();
1761
1762 observer.onSubscribe(d2);
1763
1764 b[0] = d1.isDisposed();
1765 b[1] = d2.isDisposed();
1766 } finally {
1767 cdl.countDown();
1768 }
1769 }
1770 };
1771
1772 MaybeSource<R> out = transform.apply(source);
1773
1774 out.subscribe(NoOpConsumer.INSTANCE);
1775
1776 try {
1777 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
1778 } catch (InterruptedException ex) {
1779 throw ExceptionHelper.wrapOrThrow(ex);
1780 }
1781
1782 assertEquals("First disposed?", false, b[0]);
1783 assertEquals("Second not disposed?", true, b[1]);
1784
1785 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
1786 } catch (Throwable ex) {
1787 throw ExceptionHelper.wrapOrThrow(ex);
1788 } finally {
1789 RxJavaPlugins.reset();
1790 }
1791 }
1792
1793 /**
1794 * Check if the given transformed reactive type reports multiple onSubscribe calls to
1795 * RxJavaPlugins.
1796 * @param <T> the input value type
1797 * @param transform the transform to drive an operator
1798 */
1799 public static <T> void checkDoubleOnSubscribeObservableToCompletable(Function<Observable<T>, ? extends CompletableSource> transform) {
1800 List<Throwable> errors = trackPluginErrors();
1801 try {
1802 final Boolean[] b = { null, null };
1803 final CountDownLatch cdl = new CountDownLatch(1);
1804
1805 Observable<T> source = new Observable<T>() {
1806 @Override
1807 protected void subscribeActual(Observer<? super T> observer) {
1808 try {
1809 Disposable d1 = Disposable.empty();
1810
1811 observer.onSubscribe(d1);
1812
1813 Disposable d2 = Disposable.empty();
1814
1815 observer.onSubscribe(d2);
1816
1817 b[0] = d1.isDisposed();
1818 b[1] = d2.isDisposed();
1819 } finally {
1820 cdl.countDown();
1821 }
1822 }
1823 };
1824
1825 CompletableSource out = transform.apply(source);
1826
1827 out.subscribe(NoOpConsumer.INSTANCE);
1828
1829 try {
1830 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
1831 } catch (InterruptedException ex) {
1832 throw ExceptionHelper.wrapOrThrow(ex);
1833 }
1834
1835 assertEquals("First disposed?", false, b[0]);
1836 assertEquals("Second not disposed?", true, b[1]);
1837
1838 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
1839 } catch (Throwable ex) {
1840 throw ExceptionHelper.wrapOrThrow(ex);
1841 } finally {
1842 RxJavaPlugins.reset();
1843 }
1844 }
1845
1846 /**
1847 * Check if the given transformed reactive type reports multiple onSubscribe calls to
1848 * RxJavaPlugins.
1849 * @param <T> the input value type
1850 * @param <R> the output value type
1851 * @param transform the transform to drive an operator
1852 */
1853 public static <T, R> void checkDoubleOnSubscribeFlowableToObservable(Function<Flowable<T>, ? extends ObservableSource<R>> transform) {
1854 List<Throwable> errors = trackPluginErrors();
1855 try {
1856 final Boolean[] b = { null, null };
1857 final CountDownLatch cdl = new CountDownLatch(1);
1858
1859 Flowable<T> source = new Flowable<T>() {
1860 @Override
1861 protected void subscribeActual(Subscriber<? super T> subscriber) {
1862 try {
1863 BooleanSubscription bs1 = new BooleanSubscription();
1864
1865 subscriber.onSubscribe(bs1);
1866
1867 BooleanSubscription bs2 = new BooleanSubscription();
1868
1869 subscriber.onSubscribe(bs2);
1870
1871 b[0] = bs1.isCancelled();
1872 b[1] = bs2.isCancelled();
1873 } finally {
1874 cdl.countDown();
1875 }
1876 }
1877 };
1878
1879 ObservableSource<R> out = transform.apply(source);
1880
1881 out.subscribe(NoOpConsumer.INSTANCE);
1882
1883 try {
1884 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
1885 } catch (InterruptedException ex) {
1886 throw ExceptionHelper.wrapOrThrow(ex);
1887 }
1888
1889 assertEquals("First cancelled?", false, b[0]);
1890 assertEquals("Second not cancelled?", true, b[1]);
1891
1892 assertError(errors, 0, IllegalStateException.class, "Subscription already set!");
1893 } catch (Throwable ex) {
1894 throw ExceptionHelper.wrapOrThrow(ex);
1895 } finally {
1896 RxJavaPlugins.reset();
1897 }
1898 }
1899
1900 /**
1901 * Check if the given transformed reactive type reports multiple onSubscribe calls to
1902 * RxJavaPlugins.
1903 * @param <T> the input value type
1904 * @param <R> the output value type
1905 * @param transform the transform to drive an operator
1906 */
1907 public static <T, R> void checkDoubleOnSubscribeFlowableToSingle(Function<Flowable<T>, ? extends SingleSource<R>> transform) {
1908 List<Throwable> errors = trackPluginErrors();
1909 try {
1910 final Boolean[] b = { null, null };
1911 final CountDownLatch cdl = new CountDownLatch(1);
1912
1913 Flowable<T> source = new Flowable<T>() {
1914 @Override
1915 protected void subscribeActual(Subscriber<? super T> subscriber) {
1916 try {
1917 BooleanSubscription bs1 = new BooleanSubscription();
1918
1919 subscriber.onSubscribe(bs1);
1920
1921 BooleanSubscription bs2 = new BooleanSubscription();
1922
1923 subscriber.onSubscribe(bs2);
1924
1925 b[0] = bs1.isCancelled();
1926 b[1] = bs2.isCancelled();
1927 } finally {
1928 cdl.countDown();
1929 }
1930 }
1931 };
1932
1933 SingleSource<R> out = transform.apply(source);
1934
1935 out.subscribe(NoOpConsumer.INSTANCE);
1936
1937 try {
1938 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
1939 } catch (InterruptedException ex) {
1940 throw ExceptionHelper.wrapOrThrow(ex);
1941 }
1942
1943 assertEquals("First cancelled?", false, b[0]);
1944 assertEquals("Second not cancelled?", true, b[1]);
1945
1946 assertError(errors, 0, IllegalStateException.class, "Subscription already set!");
1947 } catch (Throwable ex) {
1948 throw ExceptionHelper.wrapOrThrow(ex);
1949 } finally {
1950 RxJavaPlugins.reset();
1951 }
1952 }
1953
1954 /**
1955 * Check if the given transformed reactive type reports multiple onSubscribe calls to
1956 * RxJavaPlugins.
1957 * @param <T> the input value type
1958 * @param <R> the output value type
1959 * @param transform the transform to drive an operator
1960 */
1961 public static <T, R> void checkDoubleOnSubscribeFlowableToMaybe(Function<Flowable<T>, ? extends MaybeSource<R>> transform) {
1962 List<Throwable> errors = trackPluginErrors();
1963 try {
1964 final Boolean[] b = { null, null };
1965 final CountDownLatch cdl = new CountDownLatch(1);
1966
1967 Flowable<T> source = new Flowable<T>() {
1968 @Override
1969 protected void subscribeActual(Subscriber<? super T> subscriber) {
1970 try {
1971 BooleanSubscription bs1 = new BooleanSubscription();
1972
1973 subscriber.onSubscribe(bs1);
1974
1975 BooleanSubscription bs2 = new BooleanSubscription();
1976
1977 subscriber.onSubscribe(bs2);
1978
1979 b[0] = bs1.isCancelled();
1980 b[1] = bs2.isCancelled();
1981 } finally {
1982 cdl.countDown();
1983 }
1984 }
1985 };
1986
1987 MaybeSource<R> out = transform.apply(source);
1988
1989 out.subscribe(NoOpConsumer.INSTANCE);
1990
1991 try {
1992 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
1993 } catch (InterruptedException ex) {
1994 throw ExceptionHelper.wrapOrThrow(ex);
1995 }
1996
1997 assertEquals("First cancelled?", false, b[0]);
1998 assertEquals("Second not cancelled?", true, b[1]);
1999
2000 assertError(errors, 0, IllegalStateException.class, "Subscription already set!");
2001 } catch (Throwable ex) {
2002 throw ExceptionHelper.wrapOrThrow(ex);
2003 } finally {
2004 RxJavaPlugins.reset();
2005 }
2006 }
2007
2008 /**
2009 * Check if the given transformed reactive type reports multiple onSubscribe calls to
2010 * RxJavaPlugins.
2011 * @param <T> the input value type
2012 * @param transform the transform to drive an operator
2013 */
2014 public static <T> void checkDoubleOnSubscribeFlowableToCompletable(Function<Flowable<T>, ? extends Completable> transform) {
2015 List<Throwable> errors = trackPluginErrors();
2016 try {
2017 final Boolean[] b = { null, null };
2018 final CountDownLatch cdl = new CountDownLatch(1);
2019
2020 Flowable<T> source = new Flowable<T>() {
2021 @Override
2022 protected void subscribeActual(Subscriber<? super T> subscriber) {
2023 try {
2024 BooleanSubscription bs1 = new BooleanSubscription();
2025
2026 subscriber.onSubscribe(bs1);
2027
2028 BooleanSubscription bs2 = new BooleanSubscription();
2029
2030 subscriber.onSubscribe(bs2);
2031
2032 b[0] = bs1.isCancelled();
2033 b[1] = bs2.isCancelled();
2034 } finally {
2035 cdl.countDown();
2036 }
2037 }
2038 };
2039
2040 Completable out = transform.apply(source);
2041
2042 out.subscribe(NoOpConsumer.INSTANCE);
2043
2044 try {
2045 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
2046 } catch (InterruptedException ex) {
2047 throw ExceptionHelper.wrapOrThrow(ex);
2048 }
2049
2050 assertEquals("First cancelled?", false, b[0]);
2051 assertEquals("Second not cancelled?", true, b[1]);
2052
2053 assertError(errors, 0, IllegalStateException.class, "Subscription already set!");
2054 } catch (Throwable ex) {
2055 throw ExceptionHelper.wrapOrThrow(ex);
2056 } finally {
2057 RxJavaPlugins.reset();
2058 }
2059 }
2060
2061 /**
2062 * Check if the given transformed reactive type reports multiple onSubscribe calls to
2063 * RxJavaPlugins.
2064 * @param transform the transform to drive an operator
2065 */
2066 public static void checkDoubleOnSubscribeCompletable(Function<Completable, ? extends CompletableSource> transform) {
2067 List<Throwable> errors = trackPluginErrors();
2068 try {
2069 final Boolean[] b = { null, null };
2070 final CountDownLatch cdl = new CountDownLatch(1);
2071
2072 Completable source = new Completable() {
2073 @Override
2074 protected void subscribeActual(CompletableObserver observer) {
2075 try {
2076 Disposable d1 = Disposable.empty();
2077
2078 observer.onSubscribe(d1);
2079
2080 Disposable d2 = Disposable.empty();
2081
2082 observer.onSubscribe(d2);
2083
2084 b[0] = d1.isDisposed();
2085 b[1] = d2.isDisposed();
2086 } finally {
2087 cdl.countDown();
2088 }
2089 }
2090 };
2091
2092 CompletableSource out = transform.apply(source);
2093
2094 out.subscribe(NoOpConsumer.INSTANCE);
2095
2096 try {
2097 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
2098 } catch (InterruptedException ex) {
2099 throw ExceptionHelper.wrapOrThrow(ex);
2100 }
2101
2102 assertEquals("First disposed?", false, b[0]);
2103 assertEquals("Second not disposed?", true, b[1]);
2104
2105 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
2106 } catch (Throwable ex) {
2107 throw ExceptionHelper.wrapOrThrow(ex);
2108 } finally {
2109 RxJavaPlugins.reset();
2110 }
2111 }
2112
2113 /**
2114 * Check if the given transformed reactive type reports multiple onSubscribe calls to
2115 * RxJavaPlugins.
2116 * @param <T> the output value tye
2117 * @param transform the transform to drive an operator
2118 */
2119 public static <T> void checkDoubleOnSubscribeCompletableToMaybe(Function<Completable, ? extends MaybeSource<T>> transform) {
2120 List<Throwable> errors = trackPluginErrors();
2121 try {
2122 final Boolean[] b = { null, null };
2123 final CountDownLatch cdl = new CountDownLatch(1);
2124
2125 Completable source = new Completable() {
2126 @Override
2127 protected void subscribeActual(CompletableObserver observer) {
2128 try {
2129 Disposable d1 = Disposable.empty();
2130
2131 observer.onSubscribe(d1);
2132
2133 Disposable d2 = Disposable.empty();
2134
2135 observer.onSubscribe(d2);
2136
2137 b[0] = d1.isDisposed();
2138 b[1] = d2.isDisposed();
2139 } finally {
2140 cdl.countDown();
2141 }
2142 }
2143 };
2144
2145 MaybeSource<T> out = transform.apply(source);
2146
2147 out.subscribe(NoOpConsumer.INSTANCE);
2148
2149 try {
2150 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
2151 } catch (InterruptedException ex) {
2152 throw ExceptionHelper.wrapOrThrow(ex);
2153 }
2154
2155 assertEquals("First disposed?", false, b[0]);
2156 assertEquals("Second not disposed?", true, b[1]);
2157
2158 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
2159 } catch (Throwable ex) {
2160 throw ExceptionHelper.wrapOrThrow(ex);
2161 } finally {
2162 RxJavaPlugins.reset();
2163 }
2164 }
2165
2166 /**
2167 * Check if the given transformed reactive type reports multiple onSubscribe calls to
2168 * RxJavaPlugins.
2169 * @param <T> the output value tye
2170 * @param transform the transform to drive an operator
2171 */
2172 public static <T> void checkDoubleOnSubscribeCompletableToSingle(Function<Completable, ? extends SingleSource<T>> transform) {
2173 List<Throwable> errors = trackPluginErrors();
2174 try {
2175 final Boolean[] b = { null, null };
2176 final CountDownLatch cdl = new CountDownLatch(1);
2177
2178 Completable source = new Completable() {
2179 @Override
2180 protected void subscribeActual(CompletableObserver observer) {
2181 try {
2182 Disposable d1 = Disposable.empty();
2183
2184 observer.onSubscribe(d1);
2185
2186 Disposable d2 = Disposable.empty();
2187
2188 observer.onSubscribe(d2);
2189
2190 b[0] = d1.isDisposed();
2191 b[1] = d2.isDisposed();
2192 } finally {
2193 cdl.countDown();
2194 }
2195 }
2196 };
2197
2198 SingleSource<T> out = transform.apply(source);
2199
2200 out.subscribe(NoOpConsumer.INSTANCE);
2201
2202 try {
2203 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
2204 } catch (InterruptedException ex) {
2205 throw ExceptionHelper.wrapOrThrow(ex);
2206 }
2207
2208 assertEquals("First disposed?", false, b[0]);
2209 assertEquals("Second not disposed?", true, b[1]);
2210
2211 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
2212 } catch (Throwable ex) {
2213 throw ExceptionHelper.wrapOrThrow(ex);
2214 } finally {
2215 RxJavaPlugins.reset();
2216 }
2217 }
2218
2219 /**
2220 * Check if the given transformed reactive type reports multiple onSubscribe calls to
2221 * RxJavaPlugins.
2222 * @param transform the transform to drive an operator
2223 */
2224 public static void checkDoubleOnSubscribeCompletableToFlowable(Function<Completable, ? extends Publisher<?>> transform) {
2225 List<Throwable> errors = trackPluginErrors();
2226 try {
2227 final Boolean[] b = { null, null };
2228 final CountDownLatch cdl = new CountDownLatch(1);
2229
2230 Completable source = new Completable() {
2231 @Override
2232 protected void subscribeActual(CompletableObserver observer) {
2233 try {
2234 Disposable d1 = Disposable.empty();
2235
2236 observer.onSubscribe(d1);
2237
2238 Disposable d2 = Disposable.empty();
2239
2240 observer.onSubscribe(d2);
2241
2242 b[0] = d1.isDisposed();
2243 b[1] = d2.isDisposed();
2244 } finally {
2245 cdl.countDown();
2246 }
2247 }
2248 };
2249
2250 Publisher<?> out = transform.apply(source);
2251
2252 out.subscribe(NoOpConsumer.INSTANCE);
2253
2254 try {
2255 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
2256 } catch (InterruptedException ex) {
2257 throw ExceptionHelper.wrapOrThrow(ex);
2258 }
2259
2260 assertEquals("First disposed?", false, b[0]);
2261 assertEquals("Second not disposed?", true, b[1]);
2262
2263 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
2264 } catch (Throwable ex) {
2265 throw ExceptionHelper.wrapOrThrow(ex);
2266 } finally {
2267 RxJavaPlugins.reset();
2268 }
2269 }
2270
2271 /**
2272 * Check if the given transformed reactive type reports multiple onSubscribe calls to
2273 * RxJavaPlugins.
2274 * @param transform the transform to drive an operator
2275 */
2276 public static void checkDoubleOnSubscribeCompletableToObservable(Function<Completable, ? extends ObservableSource<?>> transform) {
2277 List<Throwable> errors = trackPluginErrors();
2278 try {
2279 final Boolean[] b = { null, null };
2280 final CountDownLatch cdl = new CountDownLatch(1);
2281
2282 Completable source = new Completable() {
2283 @Override
2284 protected void subscribeActual(CompletableObserver observer) {
2285 try {
2286 Disposable d1 = Disposable.empty();
2287
2288 observer.onSubscribe(d1);
2289
2290 Disposable d2 = Disposable.empty();
2291
2292 observer.onSubscribe(d2);
2293
2294 b[0] = d1.isDisposed();
2295 b[1] = d2.isDisposed();
2296 } finally {
2297 cdl.countDown();
2298 }
2299 }
2300 };
2301
2302 ObservableSource<?> out = transform.apply(source);
2303
2304 out.subscribe(NoOpConsumer.INSTANCE);
2305
2306 try {
2307 assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
2308 } catch (InterruptedException ex) {
2309 throw ExceptionHelper.wrapOrThrow(ex);
2310 }
2311
2312 assertEquals("First disposed?", false, b[0]);
2313 assertEquals("Second not disposed?", true, b[1]);
2314
2315 assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
2316 } catch (Throwable ex) {
2317 throw ExceptionHelper.wrapOrThrow(ex);
2318 } finally {
2319 RxJavaPlugins.reset();
2320 }
2321 }
2322
2323 /**
2324 * Check if the operator applied to a Maybe source propagates dispose properly.
2325 * @param <T> the source value type
2326 * @param <U> the output value type
2327 * @param composer the function to apply an operator to the provided Maybe source
2328 */
2329 public static <T, U> void checkDisposedMaybe(Function<Maybe<T>, ? extends MaybeSource<U>> composer) {
2330 PublishProcessor<T> pp = PublishProcessor.create();
2331
2332 TestSubscriber<U> ts = new TestSubscriber<>();
2333
2334 try {
2335 new MaybeToFlowable<>(composer.apply(pp.singleElement())).subscribe(ts);
2336 } catch (Throwable ex) {
2337 throw ExceptionHelper.wrapOrThrow(ex);
2338 }
2339
2340 assertTrue("Not subscribed to source!", pp.hasSubscribers());
2341
2342 ts.cancel();
2343
2344 assertFalse("Dispose not propagated!", pp.hasSubscribers());
2345 }
2346
2347 /**
2348 * Check if the operator applied to a Completable source propagates dispose properly.
2349 * @param composer the function to apply an operator to the provided Completable source
2350 */
2351 public static void checkDisposedCompletable(Function<Completable, ? extends CompletableSource> composer) {
2352 PublishProcessor<Integer> pp = PublishProcessor.create();
2353
2354 TestSubscriber<Integer> ts = new TestSubscriber<>();
2355
2356 try {
2357 new CompletableToFlowable<Integer>(composer.apply(pp.ignoreElements())).subscribe(ts);
2358 } catch (Throwable ex) {
2359 throw ExceptionHelper.wrapOrThrow(ex);
2360 }
2361
2362 assertTrue("Not subscribed to source!", pp.hasSubscribers());
2363
2364 ts.cancel();
2365
2366 assertFalse("Dispose not propagated!", pp.hasSubscribers());
2367 }
2368
2369 /**
2370 * Check if the operator applied to a Maybe source propagates dispose properly.
2371 * @param <T> the source value type
2372 * @param <U> the output value type
2373 * @param composer the function to apply an operator to the provided Maybe source
2374 */
2375 public static <T, U> void checkDisposedMaybeToSingle(Function<Maybe<T>, ? extends SingleSource<U>> composer) {
2376 PublishProcessor<T> pp = PublishProcessor.create();
2377
2378 TestSubscriber<U> ts = new TestSubscriber<>();
2379
2380 try {
2381 new SingleToFlowable<>(composer.apply(pp.singleElement())).subscribe(ts);
2382 } catch (Throwable ex) {
2383 throw ExceptionHelper.wrapOrThrow(ex);
2384 }
2385
2386 assertTrue(pp.hasSubscribers());
2387
2388 ts.cancel();
2389
2390 assertFalse(pp.hasSubscribers());
2391 }
2392
2393 /**
2394 * Check if the operator applied to a Maybe source propagates dispose properly.
2395 * @param <T> the source value type
2396 * @param <U> the output value type
2397 * @param composer the function to apply an operator to the provided Maybe source
2398 */
2399 public static <T, U> void checkDisposedSingleToMaybe(Function<Single<T>, ? extends MaybeSource<U>> composer) {
2400 PublishProcessor<T> pp = PublishProcessor.create();
2401
2402 TestSubscriber<U> ts = new TestSubscriber<>();
2403
2404 try {
2405 new MaybeToFlowable<>(composer.apply(pp.singleOrError())).subscribe(ts);
2406 } catch (Throwable ex) {
2407 throw ExceptionHelper.wrapOrThrow(ex);
2408 }
2409
2410 assertTrue(pp.hasSubscribers());
2411
2412 ts.cancel();
2413
2414 assertFalse(pp.hasSubscribers());
2415 }
2416
2417 /**
2418 * Check if the TestSubscriber has a CompositeException with the specified class
2419 * of Throwables in the given order.
2420 * @param ts the TestSubscriber instance
2421 * @param classes the array of expected Throwables inside the Composite
2422 */
2423 @SafeVarargs
2424 public static void assertCompositeExceptions(TestSubscriberEx<?> ts, Class<? extends Throwable>... classes) {
2425 ts
2426 .assertSubscribed()
2427 .assertError(CompositeException.class)
2428 .assertNotComplete();
2429
2430 List<Throwable> list = compositeList(ts.errors().get(0));
2431
2432 assertEquals(classes.length, list.size());
2433
2434 for (int i = 0; i < classes.length; i++) {
2435 assertError(list, i, classes[i]);
2436 }
2437 }
2438
2439 /**
2440 * Check if the TestSubscriber has a CompositeException with the specified class
2441 * of Throwables in the given order.
2442 * @param ts the TestSubscriber instance
2443 * @param classes the array of subsequent Class and String instances representing the
2444 * expected Throwable class and the expected error message
2445 */
2446 @SuppressWarnings("unchecked")
2447 public static void assertCompositeExceptions(TestSubscriberEx<?> ts, Object... classes) {
2448 ts
2449 .assertSubscribed()
2450 .assertError(CompositeException.class)
2451 .assertNotComplete();
2452
2453 List<Throwable> list = compositeList(ts.errors().get(0));
2454
2455 assertEquals(classes.length, list.size());
2456
2457 for (int i = 0; i < classes.length; i += 2) {
2458 assertError(list, i, (Class<Throwable>)classes[i], (String)classes[i + 1]);
2459 }
2460 }
2461
2462 /**
2463 * Check if the TestSubscriber has a CompositeException with the specified class
2464 * of Throwables in the given order.
2465 * @param to the TestSubscriber instance
2466 * @param classes the array of expected Throwables inside the Composite
2467 */
2468 @SafeVarargs
2469 public static void assertCompositeExceptions(TestObserverEx<?> to, Class<? extends Throwable>... classes) {
2470 to
2471 .assertSubscribed()
2472 .assertError(CompositeException.class)
2473 .assertNotComplete();
2474
2475 List<Throwable> list = compositeList(to.errors().get(0));
2476
2477 assertEquals(classes.length, list.size());
2478
2479 for (int i = 0; i < classes.length; i++) {
2480 assertError(list, i, classes[i]);
2481 }
2482 }
2483
2484 /**
2485 * Check if the TestSubscriber has a CompositeException with the specified class
2486 * of Throwables in the given order.
2487 * @param to the TestSubscriber instance
2488 * @param classes the array of subsequent Class and String instances representing the
2489 * expected Throwable class and the expected error message
2490 */
2491 @SuppressWarnings("unchecked")
2492 public static void assertCompositeExceptions(TestObserverEx<?> to, Object... classes) {
2493 to
2494 .assertSubscribed()
2495 .assertError(CompositeException.class)
2496 .assertNotComplete();
2497
2498 List<Throwable> list = compositeList(to.errors().get(0));
2499
2500 assertEquals(classes.length, list.size());
2501
2502 for (int i = 0; i < classes.length; i += 2) {
2503 assertError(list, i, (Class<Throwable>)classes[i], (String)classes[i + 1]);
2504 }
2505 }
2506
2507 /**
2508 * Emit the given values and complete the Processor.
2509 * @param <T> the value type
2510 * @param p the target processor
2511 * @param values the values to emit
2512 */
2513 @SafeVarargs
2514 public static <T> void emit(Processor<T, ?> p, T... values) {
2515 for (T v : values) {
2516 p.onNext(v);
2517 }
2518 p.onComplete();
2519 }
2520
2521 /**
2522 * Emit the given values and complete the Subject.
2523 * @param <T> the value type
2524 * @param p the target subject
2525 * @param values the values to emit
2526 */
2527 @SafeVarargs
2528 public static <T> void emit(Subject<T> p, T... values) {
2529 for (T v : values) {
2530 p.onNext(v);
2531 }
2532 p.onComplete();
2533 }
2534
2535 /**
2536 * Checks if the source is fuseable and its isEmpty/clear works properly.
2537 * @param <T> the value type
2538 * @param source the source sequence
2539 */
2540 public static <T> void checkFusedIsEmptyClear(Observable<T> source) {
2541 final CountDownLatch cdl = new CountDownLatch(1);
2542
2543 final Boolean[] state = { null, null, null, null };
2544
2545 source.subscribe(new Observer<T>() {
2546 @Override
2547 public void onSubscribe(Disposable d) {
2548 try {
2549 if (d instanceof QueueDisposable) {
2550 @SuppressWarnings("unchecked")
2551 QueueDisposable<Object> qd = (QueueDisposable<Object>) d;
2552 state[0] = true;
2553
2554 int m = qd.requestFusion(QueueFuseable.ANY);
2555
2556 if (m != QueueFuseable.NONE) {
2557 state[1] = true;
2558
2559 state[2] = qd.isEmpty();
2560
2561 qd.clear();
2562
2563 state[3] = qd.isEmpty();
2564 }
2565 }
2566 cdl.countDown();
2567 } finally {
2568 d.dispose();
2569 }
2570 }
2571
2572 @Override
2573 public void onNext(T value) {
2574
2575 }
2576
2577 @Override
2578 public void onError(Throwable e) {
2579
2580 }
2581
2582 @Override
2583 public void onComplete() {
2584
2585 }
2586 });
2587
2588 try {
2589 assertTrue(cdl.await(5, TimeUnit.SECONDS));
2590
2591 assertTrue("Not fuseable", state[0]);
2592 assertTrue("Fusion rejected", state[1]);
2593
2594 assertNotNull(state[2]);
2595 assertTrue("Did not empty", state[3]);
2596 } catch (InterruptedException ex) {
2597 throw new RuntimeException(ex);
2598 }
2599 }
2600
2601 /**
2602 * Checks if the source is fuseable and its isEmpty/clear works properly.
2603 * @param <T> the value type
2604 * @param source the source sequence
2605 */
2606 public static <T> void checkFusedIsEmptyClear(Flowable<T> source) {
2607 final CountDownLatch cdl = new CountDownLatch(1);
2608
2609 final Boolean[] state = { null, null, null, null };
2610
2611 source.subscribe(new FlowableSubscriber<T>() {
2612 @Override
2613 public void onSubscribe(Subscription s) {
2614 try {
2615 if (s instanceof QueueSubscription) {
2616 @SuppressWarnings("unchecked")
2617 QueueSubscription<Object> qs = (QueueSubscription<Object>) s;
2618 state[0] = true;
2619
2620 int m = qs.requestFusion(QueueFuseable.ANY);
2621
2622 if (m != QueueFuseable.NONE) {
2623 state[1] = true;
2624
2625 state[2] = qs.isEmpty();
2626
2627 qs.clear();
2628
2629 state[3] = qs.isEmpty();
2630 }
2631 }
2632 cdl.countDown();
2633 } finally {
2634 s.cancel();
2635 }
2636 }
2637
2638 @Override
2639 public void onNext(T value) {
2640
2641 }
2642
2643 @Override
2644 public void onError(Throwable e) {
2645
2646 }
2647
2648 @Override
2649 public void onComplete() {
2650
2651 }
2652 });
2653
2654 try {
2655 assertTrue(cdl.await(5, TimeUnit.SECONDS));
2656
2657 assertTrue("Not fuseable", state[0]);
2658 assertTrue("Fusion rejected", state[1]);
2659
2660 assertNotNull(state[2]);
2661 assertTrue("Did not empty", state[3]);
2662 } catch (InterruptedException ex) {
2663 throw new RuntimeException(ex);
2664 }
2665 }
2666
2667 /**
2668 * Returns an expanded error list of the given test consumer.
2669 * @param to the test consumer instance
2670 * @return the list
2671 */
2672 public static List<Throwable> errorList(TestObserverEx<?> to) {
2673 return compositeList(to.errors().get(0));
2674 }
2675
2676 /**
2677 * Returns an expanded error list of the given test consumer.
2678 * @param ts the test consumer instance
2679 * @return the list
2680 */
2681 public static List<Throwable> errorList(TestSubscriberEx<?> ts) {
2682 return compositeList(ts.errors().get(0));
2683 }
2684
2685 /**
2686 * Tests the given mapping of a bad Observable by emitting the good values, then an error/completion and then
2687 * a bad value followed by a TestException and and a completion.
2688 * @param <T> the value type
2689 * @param mapper the mapper that receives a bad Observable and returns a reactive base type (detected via reflection).
2690 * @param error if true, the good value emission is followed by a TestException("error"), if false then onComplete is called
2691 * @param badValue the bad value to emit if not null
2692 * @param goodValue the good value to emit before turning bad, if not null
2693 * @param expected the expected resulting values, null to ignore values received
2694 */
2695 public static <T> void checkBadSourceObservable(Function<Observable<T>, Object> mapper,
2696 final boolean error, final T goodValue, final T badValue, final Object... expected) {
2697 List<Throwable> errors = trackPluginErrors();
2698 try {
2699 Observable<T> bad = new Observable<T>() {
2700 boolean once;
2701 @Override
2702 protected void subscribeActual(Observer<? super T> observer) {
2703 observer.onSubscribe(Disposable.empty());
2704
2705 if (once) {
2706 return;
2707 }
2708 once = true;
2709
2710 if (goodValue != null) {
2711 observer.onNext(goodValue);
2712 }
2713
2714 if (error) {
2715 observer.onError(new TestException("error"));
2716 } else {
2717 observer.onComplete();
2718 }
2719
2720 if (badValue != null) {
2721 observer.onNext(badValue);
2722 }
2723 observer.onError(new TestException("second"));
2724 observer.onComplete();
2725 }
2726 };
2727
2728 Object o = mapper.apply(bad);
2729
2730 if (o instanceof ObservableSource) {
2731 ObservableSource<?> os = (ObservableSource<?>) o;
2732 TestObserverEx<Object> to = new TestObserverEx<>();
2733
2734 os.subscribe(to);
2735
2736 to.awaitDone(5, TimeUnit.SECONDS);
2737
2738 to.assertSubscribed();
2739
2740 if (expected != null) {
2741 to.assertValues(expected);
2742 }
2743 if (error) {
2744 to.assertError(TestException.class)
2745 .assertErrorMessage("error")
2746 .assertNotComplete();
2747 } else {
2748 to.assertNoErrors().assertComplete();
2749 }
2750 }
2751
2752 if (o instanceof Publisher) {
2753 Publisher<?> os = (Publisher<?>) o;
2754 TestSubscriberEx<Object> ts = new TestSubscriberEx<>();
2755
2756 os.subscribe(ts);
2757
2758 ts.awaitDone(5, TimeUnit.SECONDS);
2759
2760 ts.assertSubscribed();
2761
2762 if (expected != null) {
2763 ts.assertValues(expected);
2764 }
2765 if (error) {
2766 ts.assertError(TestException.class)
2767 .assertErrorMessage("error")
2768 .assertNotComplete();
2769 } else {
2770 ts.assertNoErrors().assertComplete();
2771 }
2772 }
2773
2774 if (o instanceof SingleSource) {
2775 SingleSource<?> os = (SingleSource<?>) o;
2776 TestObserverEx<Object> to = new TestObserverEx<>();
2777
2778 os.subscribe(to);
2779
2780 to.awaitDone(5, TimeUnit.SECONDS);
2781
2782 to.assertSubscribed();
2783
2784 if (expected != null) {
2785 to.assertValues(expected);
2786 }
2787 if (error) {
2788 to.assertError(TestException.class)
2789 .assertErrorMessage("error")
2790 .assertNotComplete();
2791 } else {
2792 to.assertNoErrors().assertComplete();
2793 }
2794 }
2795
2796 if (o instanceof MaybeSource) {
2797 MaybeSource<?> os = (MaybeSource<?>) o;
2798 TestObserverEx<Object> to = new TestObserverEx<>();
2799
2800 os.subscribe(to);
2801
2802 to.awaitDone(5, TimeUnit.SECONDS);
2803
2804 to.assertSubscribed();
2805
2806 if (expected != null) {
2807 to.assertValues(expected);
2808 }
2809 if (error) {
2810 to.assertError(TestException.class)
2811 .assertErrorMessage("error")
2812 .assertNotComplete();
2813 } else {
2814 to.assertNoErrors().assertComplete();
2815 }
2816 }
2817
2818 if (o instanceof CompletableSource) {
2819 CompletableSource os = (CompletableSource) o;
2820 TestObserverEx<Object> to = new TestObserverEx<>();
2821
2822 os.subscribe(to);
2823
2824 to.awaitDone(5, TimeUnit.SECONDS);
2825
2826 to.assertSubscribed();
2827
2828 if (expected != null) {
2829 to.assertValues(expected);
2830 }
2831 if (error) {
2832 to.assertError(TestException.class)
2833 .assertErrorMessage("error")
2834 .assertNotComplete();
2835 } else {
2836 to.assertNoErrors().assertComplete();
2837 }
2838 }
2839
2840 assertUndeliverable(errors, 0, TestException.class, "second");
2841 } catch (AssertionError ex) {
2842 throw ex;
2843 } catch (Throwable ex) {
2844 throw new RuntimeException(ex);
2845 } finally {
2846 RxJavaPlugins.reset();
2847 }
2848 }
2849
2850 /**
2851 * Tests the given mapping of a bad Observable by emitting the good values, then an error/completion and then
2852 * a bad value followed by a TestException and and a completion.
2853 * @param <T> the value type
2854 * @param mapper the mapper that receives a bad Observable and returns a reactive base type (detected via reflection).
2855 * @param error if true, the good value emission is followed by a TestException("error"), if false then onComplete is called
2856 * @param badValue the bad value to emit if not null
2857 * @param goodValue the good value to emit before turning bad, if not null
2858 * @param expected the expected resulting values, null to ignore values received
2859 */
2860 public static <T> void checkBadSourceFlowable(Function<Flowable<T>, Object> mapper,
2861 final boolean error, final T goodValue, final T badValue, final Object... expected) {
2862 List<Throwable> errors = trackPluginErrors();
2863 try {
2864 Flowable<T> bad = new Flowable<T>() {
2865 @Override
2866 protected void subscribeActual(Subscriber<? super T> subscriber) {
2867 subscriber.onSubscribe(new BooleanSubscription());
2868
2869 if (goodValue != null) {
2870 subscriber.onNext(goodValue);
2871 }
2872
2873 if (error) {
2874 subscriber.onError(new TestException("error"));
2875 } else {
2876 subscriber.onComplete();
2877 }
2878
2879 if (badValue != null) {
2880 subscriber.onNext(badValue);
2881 }
2882 subscriber.onError(new TestException("second"));
2883 subscriber.onComplete();
2884 }
2885 };
2886
2887 Object o = mapper.apply(bad);
2888
2889 if (o instanceof ObservableSource) {
2890 ObservableSource<?> os = (ObservableSource<?>) o;
2891 TestObserverEx<Object> to = new TestObserverEx<>();
2892
2893 os.subscribe(to);
2894
2895 to.awaitDone(5, TimeUnit.SECONDS);
2896
2897 to.assertSubscribed();
2898
2899 if (expected != null) {
2900 to.assertValues(expected);
2901 }
2902 if (error) {
2903 to.assertError(TestException.class)
2904 .assertErrorMessage("error")
2905 .assertNotComplete();
2906 } else {
2907 to.assertNoErrors().assertComplete();
2908 }
2909 }
2910
2911 if (o instanceof Publisher) {
2912 Publisher<?> os = (Publisher<?>) o;
2913 TestSubscriberEx<Object> ts = new TestSubscriberEx<>();
2914
2915 os.subscribe(ts);
2916
2917 ts.awaitDone(5, TimeUnit.SECONDS);
2918
2919 ts.assertSubscribed();
2920
2921 if (expected != null) {
2922 ts.assertValues(expected);
2923 }
2924 if (error) {
2925 ts.assertError(TestException.class)
2926 .assertErrorMessage("error")
2927 .assertNotComplete();
2928 } else {
2929 ts.assertNoErrors().assertComplete();
2930 }
2931 }
2932
2933 if (o instanceof SingleSource) {
2934 SingleSource<?> os = (SingleSource<?>) o;
2935 TestObserverEx<Object> to = new TestObserverEx<>();
2936
2937 os.subscribe(to);
2938
2939 to.awaitDone(5, TimeUnit.SECONDS);
2940
2941 to.assertSubscribed();
2942
2943 if (expected != null) {
2944 to.assertValues(expected);
2945 }
2946 if (error) {
2947 to.assertError(TestException.class)
2948 .assertErrorMessage("error")
2949 .assertNotComplete();
2950 } else {
2951 to.assertNoErrors().assertComplete();
2952 }
2953 }
2954
2955 if (o instanceof MaybeSource) {
2956 MaybeSource<?> os = (MaybeSource<?>) o;
2957 TestObserverEx<Object> to = new TestObserverEx<>();
2958
2959 os.subscribe(to);
2960
2961 to.awaitDone(5, TimeUnit.SECONDS);
2962
2963 to.assertSubscribed();
2964
2965 if (expected != null) {
2966 to.assertValues(expected);
2967 }
2968 if (error) {
2969 to.assertError(TestException.class)
2970 .assertErrorMessage("error")
2971 .assertNotComplete();
2972 } else {
2973 to.assertNoErrors().assertComplete();
2974 }
2975 }
2976
2977 if (o instanceof CompletableSource) {
2978 CompletableSource os = (CompletableSource) o;
2979 TestObserverEx<Object> to = new TestObserverEx<>();
2980
2981 os.subscribe(to);
2982
2983 to.awaitDone(5, TimeUnit.SECONDS);
2984
2985 to.assertSubscribed();
2986
2987 if (expected != null) {
2988 to.assertValues(expected);
2989 }
2990 if (error) {
2991 to.assertError(TestException.class)
2992 .assertErrorMessage("error")
2993 .assertNotComplete();
2994 } else {
2995 to.assertNoErrors().assertComplete();
2996 }
2997 }
2998
2999 assertUndeliverable(errors, 0, TestException.class, "second");
3000 } catch (AssertionError ex) {
3001 throw ex;
3002 } catch (Throwable ex) {
3003 throw new RuntimeException(ex);
3004 } finally {
3005 RxJavaPlugins.reset();
3006 }
3007 }
3008
3009 public static <T> void checkInvalidParallelSubscribers(ParallelFlowable<T> source) {
3010 int n = source.parallelism();
3011
3012 @SuppressWarnings("unchecked")
3013 TestSubscriber<Object>[] tss = new TestSubscriber[n + 1];
3014 for (int i = 0; i <= n; i++) {
3015 tss[i] = new TestSubscriber<>().withTag("" + i);
3016 }
3017
3018 source.subscribe(tss);
3019
3020 for (int i = 0; i <= n; i++) {
3021 tss[i].assertFailure(IllegalArgumentException.class);
3022 }
3023 }
3024
3025 /**
3026 * Creates a fuseable Observable that does not emit anything but rejects
3027 * fusion requests.
3028 * @param <T> the element type
3029 * @return the new Observable
3030 */
3031 public static <T> Observable<T> rejectObservableFusion() {
3032 return new Observable<T>() {
3033 @Override
3034 protected void subscribeActual(Observer<? super T> observer) {
3035 observer.onSubscribe(new QueueDisposable<T>() {
3036
3037 @Override
3038 public int requestFusion(int mode) {
3039 return 0;
3040 }
3041
3042 @Override
3043 public boolean offer(T value) {
3044 throw new IllegalStateException();
3045 }
3046
3047 @Override
3048 public boolean offer(T v1, T v2) {
3049 throw new IllegalStateException();
3050 }
3051
3052 @Override
3053 public T poll() throws Exception {
3054 return null;
3055 }
3056
3057 @Override
3058 public boolean isEmpty() {
3059 return true;
3060 }
3061
3062 @Override
3063 public void clear() {
3064 }
3065
3066 @Override
3067 public void dispose() {
3068 }
3069
3070 @Override
3071 public boolean isDisposed() {
3072 return false;
3073 }
3074 });
3075 }
3076 };
3077 }
3078
3079 /**
3080 * Creates a fuseable Flowable that does not emit anything but rejects
3081 * fusion requests.
3082 * @param <T> the element type
3083 * @return the new Observable
3084 */
3085 public static <T> Flowable<T> rejectFlowableFusion() {
3086 return new Flowable<T>() {
3087 @Override
3088 protected void subscribeActual(Subscriber<? super T> subscriber) {
3089 subscriber.onSubscribe(new QueueSubscription<T>() {
3090
3091 @Override
3092 public int requestFusion(int mode) {
3093 return 0;
3094 }
3095
3096 @Override
3097 public boolean offer(T value) {
3098 throw new IllegalStateException();
3099 }
3100
3101 @Override
3102 public boolean offer(T v1, T v2) {
3103 throw new IllegalStateException();
3104 }
3105
3106 @Override
3107 public T poll() throws Exception {
3108 return null;
3109 }
3110
3111 @Override
3112 public boolean isEmpty() {
3113 return true;
3114 }
3115
3116 @Override
3117 public void clear() {
3118 }
3119
3120 @Override
3121 public void cancel() {
3122 }
3123
3124 @Override
3125 public void request(long n) {
3126 }
3127 });
3128 }
3129 };
3130 }
3131
3132 static final class FlowableStripBoundary<T> extends Flowable<T> implements FlowableTransformer<T, T> {
3133
3134 final Flowable<T> source;
3135
3136 FlowableStripBoundary(Flowable<T> source) {
3137 this.source = source;
3138 }
3139
3140 @Override
3141 public Flowable<T> apply(Flowable<T> upstream) {
3142 return new FlowableStripBoundary<>(upstream);
3143 }
3144
3145 @Override
3146 protected void subscribeActual(Subscriber<? super T> s) {
3147 source.subscribe(new StripBoundarySubscriber<>(s));
3148 }
3149
3150 static final class StripBoundarySubscriber<T> implements FlowableSubscriber<T>, QueueSubscription<T> {
3151
3152 final Subscriber<? super T> downstream;
3153
3154 Subscription upstream;
3155
3156 QueueSubscription<T> qs;
3157
3158 StripBoundarySubscriber(Subscriber<? super T> downstream) {
3159 this.downstream = downstream;
3160 }
3161
3162 @SuppressWarnings("unchecked")
3163 @Override
3164 public void onSubscribe(Subscription subscription) {
3165 this.upstream = subscription;
3166 if (subscription instanceof QueueSubscription) {
3167 qs = (QueueSubscription<T>)subscription;
3168 }
3169 downstream.onSubscribe(this);
3170 }
3171
3172 @Override
3173 public void onNext(T t) {
3174 downstream.onNext(t);
3175 }
3176
3177 @Override
3178 public void onError(Throwable throwable) {
3179 downstream.onError(throwable);
3180 }
3181
3182 @Override
3183 public void onComplete() {
3184 downstream.onComplete();
3185 }
3186
3187 @Override
3188 public int requestFusion(int mode) {
3189 QueueSubscription<T> fs = qs;
3190 if (fs != null) {
3191 return fs.requestFusion(mode & ~BOUNDARY);
3192 }
3193 return NONE;
3194 }
3195
3196 @Override
3197 public boolean offer(T value) {
3198 throw new UnsupportedOperationException("Should not be called");
3199 }
3200
3201 @Override
3202 public boolean offer(T v1, T v2) {
3203 throw new UnsupportedOperationException("Should not be called");
3204 }
3205
3206 @Override
3207 public T poll() throws Throwable {
3208 return qs.poll();
3209 }
3210
3211 @Override
3212 public void clear() {
3213 qs.clear();
3214 }
3215
3216 @Override
3217 public boolean isEmpty() {
3218 return qs.isEmpty();
3219 }
3220
3221 @Override
3222 public void request(long n) {
3223 upstream.request(n);
3224 }
3225
3226 @Override
3227 public void cancel() {
3228 upstream.cancel();
3229 }
3230 }
3231 }
3232
3233 /**
3234 * Strips the {@link QueueFuseable#BOUNDARY} mode flag when the downstream calls {@link QueueSubscription#requestFusion(int)}.
3235 * <p>
3236 * By default, many operators use {@link QueueFuseable#BOUNDARY} to indicate upstream side-effects
3237 * should not leak over a fused boundary. However, some tests want to verify if {@link QueueSubscription#poll()} crashes
3238 * are handled correctly and the most convenient way is to crash {@link Flowable#map} that won't fuse with {@code BOUNDARY}
3239 * flag. This transformer strips this flag and thus allows the function of {@code map} to be executed as part of the
3240 * {@code poll()} chain.
3241 * @param <T> the element type of the flow
3242 * @return the new Transformer instance
3243 */
3244 public static <T> FlowableTransformer<T, T> flowableStripBoundary() {
3245 return new FlowableStripBoundary<>(null);
3246 }
3247
3248 static final class ObservableStripBoundary<T> extends Observable<T> implements ObservableTransformer<T, T> {
3249
3250 final Observable<T> source;
3251
3252 ObservableStripBoundary(Observable<T> source) {
3253 this.source = source;
3254 }
3255
3256 @Override
3257 public Observable<T> apply(Observable<T> upstream) {
3258 return new ObservableStripBoundary<>(upstream);
3259 }
3260
3261 @Override
3262 protected void subscribeActual(Observer<? super T> observer) {
3263 source.subscribe(new StripBoundaryObserver<>(observer));
3264 }
3265
3266 static final class StripBoundaryObserver<T> implements Observer<T>, QueueDisposable<T> {
3267
3268 final Observer<? super T> downstream;
3269
3270 Disposable upstream;
3271
3272 QueueDisposable<T> qd;
3273
3274 StripBoundaryObserver(Observer<? super T> downstream) {
3275 this.downstream = downstream;
3276 }
3277
3278 @SuppressWarnings("unchecked")
3279 @Override
3280 public void onSubscribe(Disposable d) {
3281 this.upstream = d;
3282 if (d instanceof QueueDisposable) {
3283 qd = (QueueDisposable<T>)d;
3284 }
3285 downstream.onSubscribe(this);
3286 }
3287
3288 @Override
3289 public void onNext(T t) {
3290 downstream.onNext(t);
3291 }
3292
3293 @Override
3294 public void onError(Throwable throwable) {
3295 downstream.onError(throwable);
3296 }
3297
3298 @Override
3299 public void onComplete() {
3300 downstream.onComplete();
3301 }
3302
3303 @Override
3304 public int requestFusion(int mode) {
3305 QueueDisposable<T> fs = qd;
3306 if (fs != null) {
3307 return fs.requestFusion(mode & ~BOUNDARY);
3308 }
3309 return NONE;
3310 }
3311
3312 @Override
3313 public boolean offer(T value) {
3314 throw new UnsupportedOperationException("Should not be called");
3315 }
3316
3317 @Override
3318 public boolean offer(T v1, T v2) {
3319 throw new UnsupportedOperationException("Should not be called");
3320 }
3321
3322 @Override
3323 public T poll() throws Throwable {
3324 return qd.poll();
3325 }
3326
3327 @Override
3328 public void clear() {
3329 qd.clear();
3330 }
3331
3332 @Override
3333 public boolean isEmpty() {
3334 return qd.isEmpty();
3335 }
3336
3337 @Override
3338 public void dispose() {
3339 upstream.dispose();
3340 }
3341
3342 @Override
3343 public boolean isDisposed() {
3344 return upstream.isDisposed();
3345 }
3346 }
3347 }
3348
3349 /**
3350 * Strips the {@link QueueFuseable#BOUNDARY} mode flag when the downstream calls {@link QueueDisposable#requestFusion(int)}.
3351 * <p>
3352 * By default, many operators use {@link QueueFuseable#BOUNDARY} to indicate upstream side-effects
3353 * should not leak over a fused boundary. However, some tests want to verify if {@link QueueDisposable#poll()} crashes
3354 * are handled correctly and the most convenient way is to crash {@link Observable#map} that won't fuse with {@code BOUNDARY}
3355 * flag. This transformer strips this flag and thus allows the function of {@code map} to be executed as part of the
3356 * {@code poll()} chain.
3357 * @param <T> the element type of the flow
3358 * @return the new Transformer instance
3359 */
3360 public static <T> ObservableTransformer<T, T> observableStripBoundary() {
3361 return new ObservableStripBoundary<>(null);
3362 }
3363
3364 public static <T> TestConsumerExConverters<T> testConsumer() {
3365 return new TestConsumerExConverters<>(false, 0);
3366 }
3367
3368 public static <T> TestConsumerExConverters<T> testConsumer(boolean cancelled) {
3369 return new TestConsumerExConverters<>(cancelled, 0);
3370 }
3371
3372 public static <T> TestConsumerExConverters<T> testConsumer(final int fusionMode, final boolean cancelled) {
3373 return new TestConsumerExConverters<>(cancelled, fusionMode);
3374 }
3375
3376 public static <T> TestConsumerExConverters<T> testConsumer(final boolean cancelled, final int fusionMode) {
3377 return new TestConsumerExConverters<>(cancelled, fusionMode);
3378 }
3379
3380 public static <T> FlowableConverter<T, TestSubscriberEx<T>> testSubscriber(final long initialRequest) {
3381 return testSubscriber(initialRequest, false, 0);
3382 }
3383
3384 public static <T> FlowableConverter<T, TestSubscriberEx<T>> testSubscriber(final long initialRequest, final boolean cancelled) {
3385 return testSubscriber(initialRequest, cancelled, 0);
3386 }
3387
3388 public static <T> FlowableConverter<T, TestSubscriberEx<T>> testSubscriber(final long initialRequest, final int fusionMode, final boolean cancelled) {
3389 return testSubscriber(initialRequest, cancelled, fusionMode);
3390 }
3391
3392 public static <T> FlowableConverter<T, TestSubscriberEx<T>> testSubscriber(final long initialRequest, final boolean cancelled, final int fusionMode) {
3393 return new FlowableConverter<T, TestSubscriberEx<T>>() {
3394 @Override
3395 public TestSubscriberEx<T> apply(Flowable<T> f) {
3396 TestSubscriberEx<T> tse = new TestSubscriberEx<>(initialRequest);
3397 if (cancelled) {
3398 tse.cancel();
3399 }
3400 tse.setInitialFusionMode(fusionMode);
3401 return f.subscribeWith(tse);
3402 }
3403 };
3404 }
3405
3406 public static final class TestConsumerExConverters<T> implements
3407 ObservableConverter<T, TestObserverEx<T>>,
3408 SingleConverter<T, TestObserverEx<T>>,
3409 MaybeConverter<T, TestObserverEx<T>>,
3410 CompletableConverter<TestObserverEx<Void>>,
3411 FlowableConverter<T, TestSubscriberEx<T>> {
3412
3413 final boolean cancelled;
3414
3415 final int fusionMode;
3416
3417 TestConsumerExConverters(boolean cancelled, int fusionMode) {
3418 this.cancelled = cancelled;
3419 this.fusionMode = fusionMode;
3420 }
3421
3422 @Override
3423 public TestObserverEx<Void> apply(Completable upstream) {
3424 TestObserverEx<Void> toe = new TestObserverEx<>();
3425 if (cancelled) {
3426 toe.dispose();
3427 }
3428 toe.setInitialFusionMode(fusionMode);
3429 return upstream.subscribeWith(toe);
3430 }
3431
3432 @Override
3433 public TestObserverEx<T> apply(Maybe<T> upstream) {
3434 TestObserverEx<T> toe = new TestObserverEx<>();
3435 if (cancelled) {
3436 toe.dispose();
3437 }
3438 toe.setInitialFusionMode(fusionMode);
3439 return upstream.subscribeWith(toe);
3440 }
3441
3442 @Override
3443 public TestObserverEx<T> apply(Single<T> upstream) {
3444 TestObserverEx<T> toe = new TestObserverEx<>();
3445 if (cancelled) {
3446 toe.dispose();
3447 }
3448 toe.setInitialFusionMode(fusionMode);
3449 return upstream.subscribeWith(toe);
3450 }
3451
3452 @Override
3453 public TestObserverEx<T> apply(Observable<T> upstream) {
3454 TestObserverEx<T> toe = new TestObserverEx<>();
3455 if (cancelled) {
3456 toe.dispose();
3457 }
3458 toe.setInitialFusionMode(fusionMode);
3459 return upstream.subscribeWith(toe);
3460 }
3461
3462 @Override
3463 public TestSubscriberEx<T> apply(Flowable<T> upstream) {
3464 TestSubscriberEx<T> tse = new TestSubscriberEx<>();
3465 if (cancelled) {
3466 tse.dispose();
3467 }
3468 tse.setInitialFusionMode(fusionMode);
3469 return upstream.subscribeWith(tse);
3470 }
3471 }
3472
3473 @SafeVarargs
3474 public static <T> TestSubscriberEx<T> assertValueSet(TestSubscriberEx<T> ts, T... values) {
3475 Set<T> expectedSet = new HashSet<>(Arrays.asList(values));
3476 for (T t : ts.values()) {
3477 if (!expectedSet.contains(t)) {
3478 throw ts.failWith("Item not in the set: " + BaseTestConsumer.valueAndClass(t));
3479 }
3480 }
3481 return ts;
3482 }
3483
3484 @SafeVarargs
3485 public static <T> TestObserverEx<T> assertValueSet(TestObserverEx<T> to, T... values) {
3486 Set<T> expectedSet = new HashSet<>(Arrays.asList(values));
3487 for (T t : to.values()) {
3488 if (!expectedSet.contains(t)) {
3489 throw to.failWith("Item not in the set: " + BaseTestConsumer.valueAndClass(t));
3490 }
3491 }
3492 return to;
3493 }
3494
3495 /**
3496 * Given a base reactive type name, try to find its source in the current runtime
3497 * path and return a file to it or null if not found.
3498 * @param baseClassName the class name such as {@code Maybe}
3499 * @return the File pointing to the source
3500 * @throws Exception on error
3501 */
3502 public static File findSource(String baseClassName) throws Exception {
3503 return findSource(baseClassName, "io.reactivex.rxjava3.core");
3504 }
3505
3506 /**
3507 * Given a base reactive type name, try to find its source in the current runtime
3508 * path and return a file to it or null if not found.
3509 * @param baseClassName the class name such as {@code Maybe}
3510 * @param parentPackage the parent package such as {@code io.reactivex.rxjava3.core}
3511 * @return the File pointing to the source
3512 * @throws Exception on error
3513 */
3514 public static File findSource(String baseClassName, String parentPackage) throws Exception {
3515 URL u = TestHelper.class.getResource(TestHelper.class.getSimpleName() + ".class");
3516
3517 String path = new File(u.toURI()).toString().replace('\\', '/');
3518
3519 parentPackage = parentPackage.replace(".", "/");
3520 // System.out.println(path);
3521
3522 // Locate the src/main/java directory
3523 String p = null;
3524 while (true) {
3525 int idx = path.lastIndexOf("/");
3526 if (idx < 0) {
3527 break;
3528 }
3529 path = path.substring(0, idx);
3530 String check = path + "/src/main/java";
3531
3532 if (new File(check).exists()) {
3533 p = check + "/" + parentPackage + "/" + baseClassName + ".java";
3534 break;
3535 }
3536 }
3537
3538 if (p == null) {
3539 System.err.println("Unable to locate the RxJava sources");
3540 return null;
3541 }
3542
3543 File f = new File(p);
3544
3545 if (f.canRead()) {
3546 return f;
3547 }
3548
3549 System.out.println("Can't read " + p);
3550 return null;
3551 }
3552
3553 /**
3554 * Cancels a flow before notifying a transformation and checks if an undeliverable exception
3555 * has been signaled due to the cancellation.
3556 * @param transform the operator to test
3557 * @param <T> the output type of the transformation
3558 */
3559 public static <T> void checkUndeliverableUponCancel(FlowableConverter<Integer, T> transform) {
3560 List<Throwable> errors = TestHelper.trackPluginErrors();
3561 try {
3562
3563 final SerialDisposable disposable = new SerialDisposable();
3564
3565 T result = Flowable.just(1)
3566 .map(new Function<Integer, Integer>() {
3567 @Override
3568 public Integer apply(Integer v) throws Throwable {
3569 disposable.dispose();
3570 throw new TestException();
3571 }
3572 })
3573 .to(transform);
3574
3575 if (result instanceof MaybeSource) {
3576 TestObserverEx<Object> to = new TestObserverEx<>();
3577 disposable.set(to);
3578
3579 ((MaybeSource<?>)result)
3580 .subscribe(to);
3581 to.assertEmpty();
3582 } else if (result instanceof SingleSource) {
3583 TestObserverEx<Object> to = new TestObserverEx<>();
3584 disposable.set(to);
3585
3586 ((SingleSource<?>)result)
3587 .subscribe(to);
3588 to.assertEmpty();
3589 } else if (result instanceof CompletableSource) {
3590 TestObserverEx<Object> to = new TestObserverEx<>();
3591 disposable.set(to);
3592
3593 ((CompletableSource)result)
3594 .subscribe(to);
3595 to.assertEmpty();
3596 } else if (result instanceof ObservableSource) {
3597 TestObserverEx<Object> to = new TestObserverEx<>();
3598 disposable.set(to);
3599
3600 ((ObservableSource<?>)result)
3601 .subscribe(to);
3602 to.assertEmpty();
3603 } else if (result instanceof Publisher) {
3604 TestSubscriberEx<Object> ts = new TestSubscriberEx<>();
3605 disposable.set(Disposable.fromSubscription(ts));
3606
3607 ((Publisher<?>)result)
3608 .subscribe(ts);
3609 ts.assertEmpty();
3610 } else {
3611 fail("Unsupported transformation output: " + result + " of class " + (result != null ? result.getClass() : " <null>"));
3612 }
3613
3614 assertFalse("No undeliverable errors received", errors.isEmpty());
3615 TestHelper.assertUndeliverable(errors, 0, TestException.class);
3616 } finally {
3617 RxJavaPlugins.reset();
3618 }
3619 }
3620
3621 /**
3622 * Cancels a flow before notifying a transformation and checks if an undeliverable exception
3623 * has been signaled due to the cancellation.
3624 * @param transform the operator to test
3625 * @param <T> the output type of the transformation
3626 */
3627 public static <T> void checkUndeliverableUponCancel(ObservableConverter<Integer, T> transform) {
3628 List<Throwable> errors = TestHelper.trackPluginErrors();
3629 try {
3630
3631 final SerialDisposable disposable = new SerialDisposable();
3632
3633 T result = Observable.just(1)
3634 .map(new Function<Integer, Integer>() {
3635 @Override
3636 public Integer apply(Integer v) throws Throwable {
3637 disposable.dispose();
3638 throw new TestException();
3639 }
3640 })
3641 .to(transform);
3642
3643 if (result instanceof MaybeSource) {
3644 TestObserverEx<Object> to = new TestObserverEx<>();
3645 disposable.set(to);
3646
3647 ((MaybeSource<?>)result)
3648 .subscribe(to);
3649 to.assertEmpty();
3650 } else if (result instanceof SingleSource) {
3651 TestObserverEx<Object> to = new TestObserverEx<>();
3652 disposable.set(to);
3653
3654 ((SingleSource<?>)result)
3655 .subscribe(to);
3656 to.assertEmpty();
3657 } else if (result instanceof CompletableSource) {
3658 TestObserverEx<Object> to = new TestObserverEx<>();
3659 disposable.set(to);
3660
3661 ((CompletableSource)result)
3662 .subscribe(to);
3663 to.assertEmpty();
3664 } else if (result instanceof ObservableSource) {
3665 TestObserverEx<Object> to = new TestObserverEx<>();
3666 disposable.set(to);
3667
3668 ((ObservableSource<?>)result)
3669 .subscribe(to);
3670 to.assertEmpty();
3671 } else if (result instanceof Publisher) {
3672 TestSubscriberEx<Object> ts = new TestSubscriberEx<>();
3673 disposable.set(Disposable.fromSubscription(ts));
3674
3675 ((Publisher<?>)result)
3676 .subscribe(ts);
3677 ts.assertEmpty();
3678 } else {
3679 fail("Unsupported transformation output: " + result + " of class " + (result != null ? result.getClass() : " <null>"));
3680 }
3681
3682 assertFalse("No undeliverable errors received", errors.isEmpty());
3683 TestHelper.assertUndeliverable(errors, 0, TestException.class);
3684 } finally {
3685 RxJavaPlugins.reset();
3686 }
3687 }
3688
3689 /**
3690 * Repeatedly calls System.gc() and sleeps until the current memory usage
3691 * is less than the given expected usage or the given number of wait loop/time
3692 * has passed.
3693 * @param oneSleep how many milliseconds to sleep after a GC.
3694 * @param maxLoop the maximum number of GC/sleep calls.
3695 * @param expectedMemoryUsage the memory usage in bytes at max
3696 * @return the actual memory usage after the loop
3697 * @throws InterruptedException if the sleep is interrupted
3698 */
3699 public static long awaitGC(long oneSleep, int maxLoop, long expectedMemoryUsage) throws InterruptedException {
3700 MemoryMXBean bean = ManagementFactory.getMemoryMXBean();
3701
3702 System.gc();
3703
3704 int i = maxLoop;
3705 while (i-- != 0) {
3706 long usage = bean.getHeapMemoryUsage().getUsed();
3707 if (usage <= expectedMemoryUsage) {
3708 return usage;
3709 }
3710 System.gc();
3711 Thread.sleep(oneSleep);
3712 }
3713 return bean.getHeapMemoryUsage().getUsed();
3714 }
3715
3716 /**
3717 * Enable thracking of the global errors for the duration of the action.
3718 * @param action the action to run with a list of errors encountered
3719 * @throws Throwable the exception rethrown from the action
3720 */
3721 public static void withErrorTracking(Consumer<List<Throwable>> action) throws Throwable {
3722 List<Throwable> errors = trackPluginErrors();
3723 try {
3724 action.accept(errors);
3725 } finally {
3726 RxJavaPlugins.reset();
3727 }
3728 }
3729
3730 /**
3731 * Assert if the given CompletableFuture fails with a specified error inside an ExecutionException.
3732 * @param cf the CompletableFuture to test
3733 * @param error the error class expected
3734 */
3735 public static void assertError(CompletableFuture<?> cf, Class<? extends Throwable> error) {
3736 try {
3737 cf.get();
3738 fail("Should have thrown!");
3739 } catch (Throwable ex) {
3740 if (!error.isInstance(ex.getCause())) {
3741 ex.printStackTrace();
3742 fail("Wrong cause: " + ex.getCause());
3743 }
3744 }
3745 }
3746
3747 /**
3748 * Syncs the execution of the given runnable with the execution of the
3749 * current thread.
3750 * @param run the other task to run in sync with the current thread
3751 * @param resume the latch to count down after the {@code run}
3752 */
3753 public static void raceOther(Runnable run, CountDownLatch resume) {
3754 AtomicInteger sync = new AtomicInteger(2);
3755
3756 Schedulers.single().scheduleDirect(() -> {
3757 if (sync.decrementAndGet() != 0) {
3758 while (sync.get() != 0) { }
3759 }
3760
3761 run.run();
3762
3763 resume.countDown();
3764 });
3765
3766 if (sync.decrementAndGet() != 0) {
3767 while (sync.get() != 0) { }
3768 }
3769 }
3770
3771 /**
3772 * Inserts a ConditionalSubscriber into the chain to trigger the conditional paths
3773 * without interfering with the requestFusion parts.
3774 * @param <T> the element type
3775 * @return the new FlowableTransformer instance
3776 */
3777 public static <T> FlowableTransformer<T, T> conditional() {
3778 return f -> new Flowable<T>() {
3779 @Override
3780 protected void subscribeActual(@NonNull Subscriber<@NonNull ? super T> subscriber) {
3781 f.subscribe(new ForwardingConditionalSubscriber<>(subscriber));
3782 }
3783 };
3784 }
3785
3786 /**
3787 * Wraps a Subscriber and exposes it as a fuseable conditional subscriber without interfering with
3788 * requestFusion.
3789 * @param <T> the element type
3790 */
3791 static final class ForwardingConditionalSubscriber<T> extends BasicQueueSubscription<T> implements ConditionalSubscriber<T> {
3792
3793 private static final long serialVersionUID = 365317603608134078L;
3794
3795 final Subscriber<? super T> downstream;
3796
3797 Subscription upstream;
3798
3799 QueueSubscription<T> qs;
3800
3801 ForwardingConditionalSubscriber(Subscriber<? super T> downstream) {
3802 this.downstream = downstream;
3803 }
3804
3805 @SuppressWarnings("unchecked")
3806 @Override
3807 public void onSubscribe(@NonNull Subscription s) {
3808 this.upstream = s;
3809 if (s instanceof QueueSubscription) {
3810 this.qs = (QueueSubscription<T>)s;
3811 }
3812 downstream.onSubscribe(this);
3813 }
3814
3815 @Override
3816 public void onNext(@NonNull T t) {
3817 downstream.onNext(t);
3818 }
3819
3820 @Override
3821 public boolean tryOnNext(@NonNull T t) {
3822 downstream.onNext(t);
3823 return true;
3824 }
3825
3826 @Override
3827 public void onError(Throwable t) {
3828 downstream.onError(t);
3829 }
3830
3831 @Override
3832 public void onComplete() {
3833 downstream.onComplete();
3834 }
3835
3836 @Override
3837 public int requestFusion(int mode) {
3838 return qs != null ? qs.requestFusion(mode) : 0;
3839 }
3840
3841 @Override
3842 public @Nullable T poll() throws Throwable {
3843 return qs.poll();
3844 }
3845
3846 @Override
3847 public boolean isEmpty() {
3848 return qs.isEmpty();
3849 }
3850
3851 @Override
3852 public void clear() {
3853 qs.clear();
3854 }
3855
3856 @Override
3857 public void request(long n) {
3858 upstream.request(n);
3859 }
3860
3861 @Override
3862 public void cancel() {
3863 upstream.cancel();
3864 }
3865 }
3866 }